blob: 4602d55fed8a0b94e0dd3331102e3f82730b1fdb [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) {
117 auto FirstprivateFilter = [](const OMPClause *C) -> bool {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000118 return C->getClauseKind() == OMPC_firstprivate;
119 };
Alexey Bataev69c62a92015-04-15 04:52:20 +0000120 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
121 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
122 FirstprivateFilter)> I(D.clauses(), FirstprivateFilter);
123 I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000124 auto *C = cast<OMPFirstprivateClause>(*I);
125 auto IRef = C->varlist_begin();
126 auto InitsRef = C->inits().begin();
127 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000128 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000129 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
130 EmittedAsFirstprivate.insert(OrigVD);
131 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
132 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
133 bool IsRegistered;
134 DeclRefExpr DRE(
135 const_cast<VarDecl *>(OrigVD),
136 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
137 OrigVD) != nullptr,
138 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
139 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
140 if (OrigVD->getType()->isArrayType()) {
141 // Emit VarDecl with copy init for arrays.
142 // Get the address of the original variable captured in current
143 // captured region.
144 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
145 auto Emission = EmitAutoVarAlloca(*VD);
146 auto *Init = VD->getInit();
147 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
148 // Perform simple memcpy.
149 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
150 (*IRef)->getType());
151 } else {
152 EmitOMPAggregateAssign(
153 Emission.getAllocatedAddress(), OriginalAddr,
154 (*IRef)->getType(),
155 [this, VDInit, Init](llvm::Value *DestElement,
156 llvm::Value *SrcElement) {
157 // Clean up any temporaries needed by the initialization.
158 RunCleanupsScope InitScope(*this);
159 // Emit initialization for single element.
160 LocalDeclMap[VDInit] = SrcElement;
161 EmitAnyExprToMem(Init, DestElement,
162 Init->getType().getQualifiers(),
163 /*IsInitializer*/ false);
164 LocalDeclMap.erase(VDInit);
165 });
166 }
167 EmitAutoVarCleanups(Emission);
168 return Emission.getAllocatedAddress();
169 });
170 } else {
171 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
172 // Emit private VarDecl with copy init.
173 // Remap temp VDInit variable to the address of the original
174 // variable
175 // (for proper handling of captured global variables).
176 LocalDeclMap[VDInit] = OriginalAddr;
177 EmitDecl(*VD);
178 LocalDeclMap.erase(VDInit);
179 return GetAddrOfLocalVar(VD);
180 });
181 }
182 assert(IsRegistered &&
183 "firstprivate var already registered as private");
184 // Silence the warning about unused variable.
185 (void)IsRegistered;
186 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000187 ++IRef, ++InitsRef;
188 }
189 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000190 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000191}
192
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193void CodeGenFunction::EmitOMPPrivateClause(
194 const OMPExecutableDirective &D,
195 CodeGenFunction::OMPPrivateScope &PrivateScope) {
196 auto PrivateFilter = [](const OMPClause *C) -> bool {
197 return C->getClauseKind() == OMPC_private;
198 };
Alexey Bataev50a64582015-04-22 12:24:45 +0000199 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000200 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
Alexey Bataev50a64582015-04-22 12:24:45 +0000201 I(D.clauses(), PrivateFilter);
202 I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000203 auto *C = cast<OMPPrivateClause>(*I);
204 auto IRef = C->varlist_begin();
205 for (auto IInit : C->private_copies()) {
206 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000207 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
208 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
209 bool IsRegistered =
210 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
211 // Emit private VarDecl with copy init.
212 EmitDecl(*VD);
213 return GetAddrOfLocalVar(VD);
214 });
215 assert(IsRegistered && "private var already registered as private");
216 // Silence the warning about unused variable.
217 (void)IsRegistered;
218 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000219 ++IRef;
220 }
221 }
222}
223
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000224bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
225 // threadprivate_var1 = master_threadprivate_var1;
226 // operator=(threadprivate_var2, master_threadprivate_var2);
227 // ...
228 // __kmpc_barrier(&loc, global_tid);
229 auto CopyinFilter = [](const OMPClause *C) -> bool {
230 return C->getClauseKind() == OMPC_copyin;
231 };
232 llvm::DenseSet<const VarDecl *> CopiedVars;
233 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
234 for (OMPExecutableDirective::filtered_clause_iterator<decltype(CopyinFilter)>
235 I(D.clauses(), CopyinFilter);
236 I; ++I) {
237 auto *C = cast<OMPCopyinClause>(*I);
238 auto IRef = C->varlist_begin();
239 auto ISrcRef = C->source_exprs().begin();
240 auto IDestRef = C->destination_exprs().begin();
241 for (auto *AssignOp : C->assignment_ops()) {
242 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
243 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
244 // Get the address of the master variable.
245 auto *MasterAddr = VD->isStaticLocal()
246 ? CGM.getStaticLocalDeclAddress(VD)
247 : CGM.GetAddrOfGlobal(VD);
248 // Get the address of the threadprivate variable.
249 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
250 if (CopiedVars.size() == 1) {
251 // At first check if current thread is a master thread. If it is, no
252 // need to copy data.
253 CopyBegin = createBasicBlock("copyin.not.master");
254 CopyEnd = createBasicBlock("copyin.not.master.end");
255 Builder.CreateCondBr(
256 Builder.CreateICmpNE(
257 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
258 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
259 CopyBegin, CopyEnd);
260 EmitBlock(CopyBegin);
261 }
262 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
263 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
264 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
265 SrcVD, AssignOp);
266 }
267 ++IRef;
268 ++ISrcRef;
269 ++IDestRef;
270 }
271 }
272 if (CopyEnd) {
273 // Exit out of copying procedure for non-master thread.
274 EmitBlock(CopyEnd, /*IsFinished=*/true);
275 return true;
276 }
277 return false;
278}
279
Alexey Bataev38e89532015-04-16 04:54:05 +0000280bool CodeGenFunction::EmitOMPLastprivateClauseInit(
281 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
282 auto LastprivateFilter = [](const OMPClause *C) -> bool {
283 return C->getClauseKind() == OMPC_lastprivate;
284 };
285 bool HasAtLeastOneLastprivate = false;
286 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
287 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
288 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
289 I; ++I) {
290 auto *C = cast<OMPLastprivateClause>(*I);
291 auto IRef = C->varlist_begin();
292 auto IDestRef = C->destination_exprs().begin();
293 for (auto *IInit : C->private_copies()) {
294 // Keep the address of the original variable for future update at the end
295 // of the loop.
296 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
297 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
298 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
299 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
300 DeclRefExpr DRE(
301 const_cast<VarDecl *>(OrigVD),
302 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
303 OrigVD) != nullptr,
304 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
305 return EmitLValue(&DRE).getAddress();
306 });
307 // Check if the variable is also a firstprivate: in this case IInit is
308 // not generated. Initialization of this variable will happen in codegen
309 // for 'firstprivate' clause.
310 if (!IInit)
311 continue;
312 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
313 bool IsRegistered =
314 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
315 // Emit private VarDecl with copy init.
316 EmitDecl(*VD);
317 return GetAddrOfLocalVar(VD);
318 });
319 assert(IsRegistered && "lastprivate var already registered as private");
320 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
321 }
322 ++IRef, ++IDestRef;
323 }
324 }
325 return HasAtLeastOneLastprivate;
326}
327
328void CodeGenFunction::EmitOMPLastprivateClauseFinal(
329 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
330 // Emit following code:
331 // if (<IsLastIterCond>) {
332 // orig_var1 = private_orig_var1;
333 // ...
334 // orig_varn = private_orig_varn;
335 // }
336 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
337 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
338 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
339 EmitBlock(ThenBB);
340 {
341 auto LastprivateFilter = [](const OMPClause *C) -> bool {
342 return C->getClauseKind() == OMPC_lastprivate;
343 };
344 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
345 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
346 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
347 I; ++I) {
348 auto *C = cast<OMPLastprivateClause>(*I);
349 auto IRef = C->varlist_begin();
350 auto ISrcRef = C->source_exprs().begin();
351 auto IDestRef = C->destination_exprs().begin();
352 for (auto *AssignOp : C->assignment_ops()) {
353 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
354 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
355 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
356 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
357 // Get the address of the original variable.
358 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
359 // Get the address of the private variable.
360 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
361 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
362 DestVD, SrcVD, AssignOp);
363 }
364 ++IRef;
365 ++ISrcRef;
366 ++IDestRef;
367 }
368 }
369 }
370 EmitBlock(DoneBB, /*IsFinished=*/true);
371}
372
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000373void CodeGenFunction::EmitOMPReductionClauseInit(
374 const OMPExecutableDirective &D,
375 CodeGenFunction::OMPPrivateScope &PrivateScope) {
376 auto ReductionFilter = [](const OMPClause *C) -> bool {
377 return C->getClauseKind() == OMPC_reduction;
378 };
379 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
380 ReductionFilter)> I(D.clauses(), ReductionFilter);
381 I; ++I) {
382 auto *C = cast<OMPReductionClause>(*I);
383 auto ILHS = C->lhs_exprs().begin();
384 auto IRHS = C->rhs_exprs().begin();
385 for (auto IRef : C->varlists()) {
386 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
387 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
388 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
389 // Store the address of the original variable associated with the LHS
390 // implicit variable.
391 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
392 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
393 CapturedStmtInfo->lookup(OrigVD) != nullptr,
394 IRef->getType(), VK_LValue, IRef->getExprLoc());
395 return EmitLValue(&DRE).getAddress();
396 });
397 // Emit reduction copy.
398 bool IsRegistered =
399 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
400 // Emit private VarDecl with reduction init.
401 EmitDecl(*PrivateVD);
402 return GetAddrOfLocalVar(PrivateVD);
403 });
404 assert(IsRegistered && "private var already registered as private");
405 // Silence the warning about unused variable.
406 (void)IsRegistered;
407 ++ILHS, ++IRHS;
408 }
409 }
410}
411
412void CodeGenFunction::EmitOMPReductionClauseFinal(
413 const OMPExecutableDirective &D) {
414 llvm::SmallVector<const Expr *, 8> LHSExprs;
415 llvm::SmallVector<const Expr *, 8> RHSExprs;
416 llvm::SmallVector<const Expr *, 8> ReductionOps;
417 auto ReductionFilter = [](const OMPClause *C) -> bool {
418 return C->getClauseKind() == OMPC_reduction;
419 };
420 bool HasAtLeastOneReduction = false;
421 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
422 ReductionFilter)> I(D.clauses(), ReductionFilter);
423 I; ++I) {
424 HasAtLeastOneReduction = true;
425 auto *C = cast<OMPReductionClause>(*I);
426 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
427 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
428 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
429 }
430 if (HasAtLeastOneReduction) {
431 // Emit nowait reduction if nowait clause is present or directive is a
432 // parallel directive (it always has implicit barrier).
433 CGM.getOpenMPRuntime().emitReduction(
434 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
435 D.getSingleClause(OMPC_nowait) ||
436 isOpenMPParallelDirective(D.getDirectiveKind()));
437 }
438}
439
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000440static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
441 const OMPExecutableDirective &S,
442 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000443 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000444 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
445 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
446 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000447 if (auto C = S.getSingleClause(OMPC_num_threads)) {
448 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
449 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
450 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
451 /*IgnoreResultAssign*/ true);
452 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
453 CGF, NumThreads, NumThreadsClause->getLocStart());
454 }
455 const Expr *IfCond = nullptr;
456 if (auto C = S.getSingleClause(OMPC_if)) {
457 IfCond = cast<OMPIfClause>(C)->getCondition();
458 }
459 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
460 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000461}
462
463void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
464 LexicalScope Scope(*this, S.getSourceRange());
465 // Emit parallel region as a standalone region.
466 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
467 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000468 bool Copyins = CGF.EmitOMPCopyinClause(S);
469 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
470 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000471 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000472 // initialization of firstprivate variables or propagation master's thread
473 // values of threadprivate variables to local instances of that variables
474 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000475 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
476 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 }
478 CGF.EmitOMPPrivateClause(S, PrivateScope);
479 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
480 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000481 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000482 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000483 // Emit implicit barrier at the end of the 'parallel' directive.
484 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
485 OMPD_unknown);
486 };
487 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000488}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000489
Alexander Musmand196ef22014-10-07 08:57:09 +0000490void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000491 bool SeparateIter) {
492 RunCleanupsScope BodyScope(*this);
493 // Update counters values on current iteration.
494 for (auto I : S.updates()) {
495 EmitIgnoredExpr(I);
496 }
Alexander Musman3276a272015-03-21 10:12:56 +0000497 // Update the linear variables.
498 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
499 for (auto U : C->updates()) {
500 EmitIgnoredExpr(U);
501 }
502 }
503
Alexander Musmana5f070a2014-10-01 06:03:56 +0000504 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000505 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000506 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
507 // Emit loop body.
508 EmitStmt(S.getBody());
509 // The end (updates/cleanups).
510 EmitBlock(Continue.getBlock());
511 BreakContinueStack.pop_back();
512 if (SeparateIter) {
513 // TODO: Update lastprivates if the SeparateIter flag is true.
514 // This will be implemented in a follow-up OMPLastprivateClause patch, but
515 // result should be still correct without it, as we do not make these
516 // variables private yet.
517 }
518}
519
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000520void CodeGenFunction::EmitOMPInnerLoop(
521 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
522 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000523 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
524 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000525 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000526 auto Cnt = getPGORegionCounter(&S);
527
528 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000529 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000530 EmitBlock(CondBlock);
531 LoopStack.push(CondBlock);
532
533 // If there are any cleanups between here and the loop-exit scope,
534 // create a block to stage a loop exit along.
535 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000536 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000537 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000538
Alexander Musmand196ef22014-10-07 08:57:09 +0000539 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000540
Alexey Bataev2df54a02015-03-12 08:53:29 +0000541 // Emit condition.
542 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, Cnt.getCount());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000543 if (ExitBlock != LoopExit.getBlock()) {
544 EmitBlock(ExitBlock);
545 EmitBranchThroughCleanup(LoopExit);
546 }
547
548 EmitBlock(LoopBody);
549 Cnt.beginRegion(Builder);
550
551 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000552 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000553 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
554
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000555 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000556
557 // Emit "IV = IV + 1" and a back-edge to the condition block.
558 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000559 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000560 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000561 BreakContinueStack.pop_back();
562 EmitBranch(CondBlock);
563 LoopStack.pop();
564 // Emit the fall-through block.
565 EmitBlock(LoopExit.getBlock());
566}
567
568void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
569 auto IC = S.counters().begin();
570 for (auto F : S.finals()) {
571 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
572 EmitIgnoredExpr(F);
573 }
574 ++IC;
575 }
Alexander Musman3276a272015-03-21 10:12:56 +0000576 // Emit the final values of the linear variables.
577 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
578 for (auto F : C->finals()) {
579 EmitIgnoredExpr(F);
580 }
581 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000582}
583
Alexander Musman09184fe2014-09-30 05:29:28 +0000584static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
585 const OMPAlignedClause &Clause) {
586 unsigned ClauseAlignment = 0;
587 if (auto AlignmentExpr = Clause.getAlignment()) {
588 auto AlignmentCI =
589 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
590 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
591 }
592 for (auto E : Clause.varlists()) {
593 unsigned Alignment = ClauseAlignment;
594 if (Alignment == 0) {
595 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000596 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000597 // alignments for SIMD instructions on the target platforms are assumed.
598 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
599 E->getType());
600 }
601 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
602 "alignment is not power of 2");
603 if (Alignment != 0) {
604 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
605 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
606 }
607 }
608}
609
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000610static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
611 CodeGenFunction::OMPPrivateScope &LoopScope,
612 ArrayRef<Expr *> Counters) {
613 for (auto *E : Counters) {
614 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
615 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
616 // Emit var without initialization.
617 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
618 CGF.EmitAutoVarCleanups(VarEmission);
619 return VarEmission.getAllocatedAddress();
620 });
621 assert(IsRegistered && "counter already registered as private");
622 // Silence the warning about unused variable.
623 (void)IsRegistered;
624 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000625}
626
Alexey Bataev62dbb972015-04-22 11:59:37 +0000627static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
628 const Expr *Cond, llvm::BasicBlock *TrueBlock,
629 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
630 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
631 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
632 const VarDecl *IVDecl =
633 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
634 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
635 // Emit var without initialization.
636 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
637 CGF.EmitAutoVarCleanups(VarEmission);
638 return VarEmission.getAllocatedAddress();
639 });
640 assert(IsRegistered && "counter already registered as private");
641 // Silence the warning about unused variable.
642 (void)IsRegistered;
643 (void)PreCondScope.Privatize();
644 // Initialize internal counter to 0 to calculate initial values of real
645 // counters.
646 LValue IV = CGF.EmitLValue(S.getIterationVariable());
647 CGF.EmitStoreOfScalar(
648 llvm::ConstantInt::getNullValue(
649 IV.getAddress()->getType()->getPointerElementType()),
650 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
651 // Get initial values of real counters.
652 for (auto I : S.updates()) {
653 CGF.EmitIgnoredExpr(I);
654 }
655 // Check that loop is executed at least one time.
656 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
657}
658
Alexander Musman3276a272015-03-21 10:12:56 +0000659static void
660EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
661 CodeGenFunction::OMPPrivateScope &PrivateScope) {
662 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
663 for (auto *E : Clause->varlists()) {
664 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
665 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
666 // Emit var without initialization.
667 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
668 CGF.EmitAutoVarCleanups(VarEmission);
669 return VarEmission.getAllocatedAddress();
670 });
671 assert(IsRegistered && "linear var already registered as private");
672 // Silence the warning about unused variable.
673 (void)IsRegistered;
674 }
675 }
676}
677
Alexander Musman515ad8c2014-05-22 08:54:05 +0000678void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000679 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
680 // Pragma 'simd' code depends on presence of 'lastprivate'.
681 // If present, we have to separate last iteration of the loop:
682 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000683 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000684 // for (IV in 0..LastIteration-1) BODY;
685 // BODY with updates of lastprivate vars;
686 // <Final counter/linear vars updates>;
687 // }
688 //
689 // otherwise (when there's no lastprivate):
690 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000691 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000692 // for (IV in 0..LastIteration) BODY;
693 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000694 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000695 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000696
Alexey Bataev62dbb972015-04-22 11:59:37 +0000697 // Emit: if (PreCond) - begin.
698 // If the condition constant folds and can be elided, avoid emitting the
699 // whole loop.
700 bool CondConstant;
701 llvm::BasicBlock *ContBlock = nullptr;
702 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
703 if (!CondConstant)
704 return;
705 } else {
706 RegionCounter Cnt = CGF.getPGORegionCounter(&S);
707 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
708 ContBlock = CGF.createBasicBlock("simd.if.end");
709 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
710 CGF.EmitBlock(ThenBlock);
711 Cnt.beginRegion(CGF.Builder);
712 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000713 // Walk clauses and process safelen/lastprivate.
714 bool SeparateIter = false;
715 CGF.LoopStack.setParallel();
716 CGF.LoopStack.setVectorizerEnable(true);
717 for (auto C : S.clauses()) {
718 switch (C->getClauseKind()) {
719 case OMPC_safelen: {
720 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
721 AggValueSlot::ignored(), true);
722 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
723 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
724 // In presence of finite 'safelen', it may be unsafe to mark all
725 // the memory instructions parallel, because loop-carried
726 // dependences of 'safelen' iterations are possible.
727 CGF.LoopStack.setParallel(false);
728 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000729 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000730 case OMPC_aligned:
731 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
732 break;
733 case OMPC_lastprivate:
734 SeparateIter = true;
735 break;
736 default:
737 // Not handled yet
738 ;
739 }
740 }
Alexander Musman3276a272015-03-21 10:12:56 +0000741
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000742 // Emit inits for the linear variables.
743 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
744 for (auto Init : C->inits()) {
745 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
746 CGF.EmitVarDecl(*D);
747 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000748 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000749
750 // Emit the loop iteration variable.
751 const Expr *IVExpr = S.getIterationVariable();
752 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
753 CGF.EmitVarDecl(*IVDecl);
754 CGF.EmitIgnoredExpr(S.getInit());
755
756 // Emit the iterations count variable.
757 // If it is not a variable, Sema decided to calculate iterations count on
758 // each
759 // iteration (e.g., it is foldable into a constant).
760 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
761 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
762 // Emit calculation of the iterations count.
763 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000764 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000765
766 // Emit the linear steps for the linear clauses.
767 // If a step is not constant, it is pre-calculated before the loop.
768 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
769 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
770 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
771 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
772 // Emit calculation of the linear step.
773 CGF.EmitIgnoredExpr(CS);
774 }
775 }
776
Alexey Bataev62dbb972015-04-22 11:59:37 +0000777 {
778 OMPPrivateScope LoopScope(CGF);
779 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
780 EmitPrivateLinearVars(CGF, S, LoopScope);
781 CGF.EmitOMPPrivateClause(S, LoopScope);
782 (void)LoopScope.Privatize();
783 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
784 S.getCond(SeparateIter), S.getInc(),
785 [&S](CodeGenFunction &CGF) {
786 CGF.EmitOMPLoopBody(S);
787 CGF.EmitStopPoint(&S);
788 },
789 [](CodeGenFunction &) {});
790 if (SeparateIter) {
791 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000792 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000793 }
794 CGF.EmitOMPSimdFinal(S);
795 // Emit: if (PreCond) - end.
796 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000797 CGF.EmitBranch(ContBlock);
798 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000799 }
800 };
801 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000802}
803
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000804void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
805 const OMPLoopDirective &S,
806 OMPPrivateScope &LoopScope,
807 llvm::Value *LB, llvm::Value *UB,
808 llvm::Value *ST, llvm::Value *IL,
809 llvm::Value *Chunk) {
810 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000811
812 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
813 const bool Dynamic = RT.isDynamic(ScheduleKind);
814
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000815 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
816 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000817
818 // Emit outer loop.
819 //
820 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000821 // When schedule(dynamic,chunk_size) is specified, the iterations are
822 // distributed to threads in the team in chunks as the threads request them.
823 // Each thread executes a chunk of iterations, then requests another chunk,
824 // until no chunks remain to be distributed. Each chunk contains chunk_size
825 // iterations, except for the last chunk to be distributed, which may have
826 // fewer iterations. When no chunk_size is specified, it defaults to 1.
827 //
828 // When schedule(guided,chunk_size) is specified, the iterations are assigned
829 // to threads in the team in chunks as the executing threads request them.
830 // Each thread executes a chunk of iterations, then requests another chunk,
831 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
832 // each chunk is proportional to the number of unassigned iterations divided
833 // by the number of threads in the team, decreasing to 1. For a chunk_size
834 // with value k (greater than 1), the size of each chunk is determined in the
835 // same way, with the restriction that the chunks do not contain fewer than k
836 // iterations (except for the last chunk to be assigned, which may have fewer
837 // than k iterations).
838 //
839 // When schedule(auto) is specified, the decision regarding scheduling is
840 // delegated to the compiler and/or runtime system. The programmer gives the
841 // implementation the freedom to choose any possible mapping of iterations to
842 // threads in the team.
843 //
844 // When schedule(runtime) is specified, the decision regarding scheduling is
845 // deferred until run time, and the schedule and chunk size are taken from the
846 // run-sched-var ICV. If the ICV is set to auto, the schedule is
847 // implementation defined
848 //
849 // while(__kmpc_dispatch_next(&LB, &UB)) {
850 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000851 // while (idx <= UB) { BODY; ++idx;
852 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
853 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000854 // }
855 //
856 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000857 // When schedule(static, chunk_size) is specified, iterations are divided into
858 // chunks of size chunk_size, and the chunks are assigned to the threads in
859 // the team in a round-robin fashion in the order of the thread number.
860 //
861 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
862 // while (idx <= UB) { BODY; ++idx; } // inner loop
863 // LB = LB + ST;
864 // UB = UB + ST;
865 // }
866 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000867
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000868 const Expr *IVExpr = S.getIterationVariable();
869 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
870 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
871
Alexander Musman92bdaab2015-03-12 13:37:50 +0000872 RT.emitForInit(
873 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
874 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
875 Chunk);
876
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000877 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
878
879 // Start the loop with a block that tests the condition.
880 auto CondBlock = createBasicBlock("omp.dispatch.cond");
881 EmitBlock(CondBlock);
882 LoopStack.push(CondBlock);
883
884 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000885 if (!Dynamic) {
886 // UB = min(UB, GlobalUB)
887 EmitIgnoredExpr(S.getEnsureUpperBound());
888 // IV = LB
889 EmitIgnoredExpr(S.getInit());
890 // IV < UB
891 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
892 } else {
893 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
894 IL, LB, UB, ST);
895 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000896
897 // If there are any cleanups between here and the loop-exit scope,
898 // create a block to stage a loop exit along.
899 auto ExitBlock = LoopExit.getBlock();
900 if (LoopScope.requiresCleanups())
901 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
902
903 auto LoopBody = createBasicBlock("omp.dispatch.body");
904 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
905 if (ExitBlock != LoopExit.getBlock()) {
906 EmitBlock(ExitBlock);
907 EmitBranchThroughCleanup(LoopExit);
908 }
909 EmitBlock(LoopBody);
910
Alexander Musman92bdaab2015-03-12 13:37:50 +0000911 // Emit "IV = LB" (in case of static schedule, we have already calculated new
912 // LB for loop condition and emitted it above).
913 if (Dynamic)
914 EmitIgnoredExpr(S.getInit());
915
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000916 // Create a block for the increment.
917 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
918 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
919
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000920 bool DynamicWithOrderedClause =
921 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
922 SourceLocation Loc = S.getLocStart();
923 EmitOMPInnerLoop(
924 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
925 S.getInc(),
926 [&S](CodeGenFunction &CGF) {
927 CGF.EmitOMPLoopBody(S);
928 CGF.EmitStopPoint(&S);
929 },
930 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
931 if (DynamicWithOrderedClause) {
932 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
933 CGF, Loc, IVSize, IVSigned);
934 }
935 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000936
937 EmitBlock(Continue.getBlock());
938 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000939 if (!Dynamic) {
940 // Emit "LB = LB + Stride", "UB = UB + Stride".
941 EmitIgnoredExpr(S.getNextLowerBound());
942 EmitIgnoredExpr(S.getNextUpperBound());
943 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000944
945 EmitBranch(CondBlock);
946 LoopStack.pop();
947 // Emit the fall-through block.
948 EmitBlock(LoopExit.getBlock());
949
950 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000951 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000952 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000953}
954
Alexander Musmanc6388682014-12-15 07:07:06 +0000955/// \brief Emit a helper variable and return corresponding lvalue.
956static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
957 const DeclRefExpr *Helper) {
958 auto VDecl = cast<VarDecl>(Helper->getDecl());
959 CGF.EmitVarDecl(*VDecl);
960 return CGF.EmitLValue(Helper);
961}
962
Alexey Bataev38e89532015-04-16 04:54:05 +0000963bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000964 // Emit the loop iteration variable.
965 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
966 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
967 EmitVarDecl(*IVDecl);
968
969 // Emit the iterations count variable.
970 // If it is not a variable, Sema decided to calculate iterations count on each
971 // iteration (e.g., it is foldable into a constant).
972 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
973 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
974 // Emit calculation of the iterations count.
975 EmitIgnoredExpr(S.getCalcLastIteration());
976 }
977
978 auto &RT = CGM.getOpenMPRuntime();
979
Alexey Bataev38e89532015-04-16 04:54:05 +0000980 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +0000981 // Check pre-condition.
982 {
983 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +0000984 // If the condition constant folds and can be elided, avoid emitting the
985 // whole loop.
986 bool CondConstant;
987 llvm::BasicBlock *ContBlock = nullptr;
988 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
989 if (!CondConstant)
990 return false;
991 } else {
992 RegionCounter Cnt = getPGORegionCounter(&S);
993 auto *ThenBlock = createBasicBlock("omp.precond.then");
994 ContBlock = createBasicBlock("omp.precond.end");
995 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
996 Cnt.getCount());
997 EmitBlock(ThenBlock);
998 Cnt.beginRegion(Builder);
999 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001000 // Emit 'then' code.
1001 {
1002 // Emit helper vars inits.
1003 LValue LB =
1004 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1005 LValue UB =
1006 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1007 LValue ST =
1008 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1009 LValue IL =
1010 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1011
1012 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001013 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1014 // Emit implicit barrier to synchronize threads and avoid data races on
1015 // initialization of firstprivate variables.
1016 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1017 OMPD_unknown);
1018 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001019 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001020 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001021 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001022 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001023 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001024
1025 // Detect the loop schedule kind and chunk.
1026 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1027 llvm::Value *Chunk = nullptr;
1028 if (auto C = cast_or_null<OMPScheduleClause>(
1029 S.getSingleClause(OMPC_schedule))) {
1030 ScheduleKind = C->getScheduleKind();
1031 if (auto Ch = C->getChunkSize()) {
1032 Chunk = EmitScalarExpr(Ch);
1033 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1034 S.getIterationVariable()->getType());
1035 }
1036 }
1037 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1038 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1039 if (RT.isStaticNonchunked(ScheduleKind,
1040 /* Chunked */ Chunk != nullptr)) {
1041 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1042 // When no chunk_size is specified, the iteration space is divided into
1043 // chunks that are approximately equal in size, and at most one chunk is
1044 // distributed to each thread. Note that the size of the chunks is
1045 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001046 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1047 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1048 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001049 // UB = min(UB, GlobalUB);
1050 EmitIgnoredExpr(S.getEnsureUpperBound());
1051 // IV = LB;
1052 EmitIgnoredExpr(S.getInit());
1053 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001054 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1055 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001056 [&S](CodeGenFunction &CGF) {
1057 CGF.EmitOMPLoopBody(S);
1058 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001059 },
1060 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001061 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001062 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001063 } else {
1064 // Emit the outer loop, which requests its work chunk [LB..UB] from
1065 // runtime and runs the inner loop to process it.
1066 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1067 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1068 Chunk);
1069 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001070 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1072 if (HasLastprivateClause)
1073 EmitOMPLastprivateClauseFinal(
1074 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001075 }
1076 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001077 if (ContBlock) {
1078 EmitBranch(ContBlock);
1079 EmitBlock(ContBlock, true);
1080 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001081 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001082 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001083}
1084
1085void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001086 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001087 bool HasLastprivates = false;
1088 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1089 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1090 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001091 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001092
1093 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001094 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001095 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1096 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001097}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001098
Alexander Musmanf82886e2014-09-18 05:12:34 +00001099void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1100 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1101}
1102
Alexey Bataev2df54a02015-03-12 08:53:29 +00001103static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1104 const Twine &Name,
1105 llvm::Value *Init = nullptr) {
1106 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1107 if (Init)
1108 CGF.EmitScalarInit(Init, LVal);
1109 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001110}
1111
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001112static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1113 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001114 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1115 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1116 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001117 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
1118 auto &C = CGF.CGM.getContext();
1119 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1120 // Emit helper vars inits.
1121 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1122 CGF.Builder.getInt32(0));
1123 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1124 LValue UB =
1125 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1126 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1127 CGF.Builder.getInt32(1));
1128 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1129 CGF.Builder.getInt32(0));
1130 // Loop counter.
1131 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1132 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001133 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001135 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001136 // Generate condition for loop.
1137 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1138 OK_Ordinary, S.getLocStart(),
1139 /*fpContractable=*/false);
1140 // Increment for loop counter.
1141 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1142 OK_Ordinary, S.getLocStart());
1143 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1144 // Iterate through all sections and emit a switch construct:
1145 // switch (IV) {
1146 // case 0:
1147 // <SectionStmt[0]>;
1148 // break;
1149 // ...
1150 // case <NumSection> - 1:
1151 // <SectionStmt[<NumSection> - 1]>;
1152 // break;
1153 // }
1154 // .omp.sections.exit:
1155 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1156 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1157 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1158 CS->size());
1159 unsigned CaseNumber = 0;
1160 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1161 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1162 CGF.EmitBlock(CaseBB);
1163 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1164 CGF.EmitStmt(*C);
1165 CGF.EmitBranch(ExitBB);
1166 }
1167 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1168 };
1169 // Emit static non-chunked loop.
1170 CGF.CGM.getOpenMPRuntime().emitForInit(
1171 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1172 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1173 ST.getAddress());
1174 // UB = min(UB, GlobalUB);
1175 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1176 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1177 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1178 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1179 // IV = LB;
1180 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1181 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001182 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1183 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001184 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001185 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001186 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001188 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1189 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001190 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001191 // If only one section is found - no need to generate loop, emit as a single
1192 // region.
1193 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
1194 CGF.EmitStmt(Stmt);
1195 CGF.EnsureInsertPoint();
1196 };
1197 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1198 llvm::None, llvm::None,
1199 llvm::None, llvm::None);
1200 return OMPD_single;
1201}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001202
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001203void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1204 LexicalScope Scope(*this, S.getSourceRange());
1205 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001206 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001207 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001208 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001209 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001210}
1211
1212void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001213 LexicalScope Scope(*this, S.getSourceRange());
1214 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1215 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1216 CGF.EnsureInsertPoint();
1217 };
1218 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001219}
1220
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001221void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001222 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001223 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001224 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001225 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001226 // Check if there are any 'copyprivate' clauses associated with this
1227 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001228 // construct.
1229 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1230 return C->getClauseKind() == OMPC_copyprivate;
1231 };
1232 // Build a list of copyprivate variables along with helper expressions
1233 // (<source>, <destination>, <destination>=<source> expressions)
1234 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1235 CopyprivateFilter)> CopyprivateIter;
1236 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1237 auto *C = cast<OMPCopyprivateClause>(*I);
1238 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001239 DestExprs.append(C->destination_exprs().begin(),
1240 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001241 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001242 AssignmentOps.append(C->assignment_ops().begin(),
1243 C->assignment_ops().end());
1244 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001246 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001247 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1248 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1249 CGF.EnsureInsertPoint();
1250 };
1251 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001252 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001253 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001254 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001255 if (!S.getSingleClause(OMPC_nowait)) {
1256 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1257 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001258}
1259
Alexey Bataev8d690652014-12-04 07:23:53 +00001260void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001261 LexicalScope Scope(*this, S.getSourceRange());
1262 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1263 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1264 CGF.EnsureInsertPoint();
1265 };
1266 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001267}
1268
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001269void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001270 LexicalScope Scope(*this, S.getSourceRange());
1271 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1272 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1273 CGF.EnsureInsertPoint();
1274 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001275 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001276 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001277}
1278
Alexey Bataev671605e2015-04-13 05:28:11 +00001279void CodeGenFunction::EmitOMPParallelForDirective(
1280 const OMPParallelForDirective &S) {
1281 // Emit directive as a combined directive that consists of two implicit
1282 // directives: 'parallel' with 'for' directive.
1283 LexicalScope Scope(*this, S.getSourceRange());
1284 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1285 CGF.EmitOMPWorksharingLoop(S);
1286 // Emit implicit barrier at the end of parallel region, but this barrier
1287 // is at the end of 'for' directive, so emit it as the implicit barrier for
1288 // this 'for' directive.
1289 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1290 OMPD_parallel);
1291 };
1292 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001293}
1294
Alexander Musmane4e893b2014-09-23 09:33:00 +00001295void CodeGenFunction::EmitOMPParallelForSimdDirective(
1296 const OMPParallelForSimdDirective &) {
1297 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1298}
1299
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001300void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001301 const OMPParallelSectionsDirective &S) {
1302 // Emit directive as a combined directive that consists of two implicit
1303 // directives: 'parallel' with 'sections' directive.
1304 LexicalScope Scope(*this, S.getSourceRange());
1305 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1306 (void)emitSections(CGF, S);
1307 // Emit implicit barrier at the end of parallel region.
1308 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1309 OMPD_parallel);
1310 };
1311 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001312}
1313
Alexey Bataev62b63b12015-03-10 07:28:44 +00001314void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1315 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001317 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1318 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1319 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001320 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001321 // The first function argument for tasks is a thread id, the second one is a
1322 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1324 if (*PartId) {
1325 // TODO: emit code for untied tasks.
1326 }
1327 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1328 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001329 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001330 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001331 // Check if we should emit tied or untied task.
1332 bool Tied = !S.getSingleClause(OMPC_untied);
1333 // Check if the task is final
1334 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1335 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1336 // If the condition constant folds and can be elided, try to avoid emitting
1337 // the condition and the dead arm of the if/else.
1338 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1339 bool CondConstant;
1340 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1341 Final.setInt(CondConstant);
1342 else
1343 Final.setPointer(EvaluateExprAsBool(Cond));
1344 } else {
1345 // By default the task is not final.
1346 Final.setInt(/*IntVal=*/false);
1347 }
1348 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001349 const Expr *IfCond = nullptr;
1350 if (auto C = S.getSingleClause(OMPC_if)) {
1351 IfCond = cast<OMPIfClause>(C)->getCondition();
1352 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001353 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001354 OutlinedFn, SharedsTy, CapturedStruct,
1355 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001356}
1357
Alexey Bataev9f797f32015-02-05 05:57:51 +00001358void CodeGenFunction::EmitOMPTaskyieldDirective(
1359 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001360 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001361}
1362
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001363void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001365}
1366
Alexey Bataev2df347a2014-07-18 10:17:07 +00001367void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1368 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1369}
1370
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001371void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001372 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1373 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1374 auto FlushClause = cast<OMPFlushClause>(C);
1375 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1376 FlushClause->varlist_end());
1377 }
1378 return llvm::None;
1379 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001380}
1381
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001382void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1383 LexicalScope Scope(*this, S.getSourceRange());
1384 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1385 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1386 CGF.EnsureInsertPoint();
1387 };
1388 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001389}
1390
Alexey Bataevb57056f2015-01-22 06:17:56 +00001391static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1392 QualType SrcType, QualType DestType) {
1393 assert(CGF.hasScalarEvaluationKind(DestType) &&
1394 "DestType must have scalar evaluation kind.");
1395 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1396 return Val.isScalar()
1397 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1398 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1399 DestType);
1400}
1401
1402static CodeGenFunction::ComplexPairTy
1403convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1404 QualType DestType) {
1405 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1406 "DestType must have complex evaluation kind.");
1407 CodeGenFunction::ComplexPairTy ComplexVal;
1408 if (Val.isScalar()) {
1409 // Convert the input element to the element type of the complex.
1410 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1411 auto ScalarVal =
1412 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1413 ComplexVal = CodeGenFunction::ComplexPairTy(
1414 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1415 } else {
1416 assert(Val.isComplex() && "Must be a scalar or complex.");
1417 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1418 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1419 ComplexVal.first = CGF.EmitScalarConversion(
1420 Val.getComplexVal().first, SrcElementType, DestElementType);
1421 ComplexVal.second = CGF.EmitScalarConversion(
1422 Val.getComplexVal().second, SrcElementType, DestElementType);
1423 }
1424 return ComplexVal;
1425}
1426
1427static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1428 const Expr *X, const Expr *V,
1429 SourceLocation Loc) {
1430 // v = x;
1431 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1432 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1433 LValue XLValue = CGF.EmitLValue(X);
1434 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001435 RValue Res = XLValue.isGlobalReg()
1436 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1437 : CGF.EmitAtomicLoad(XLValue, Loc,
1438 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001439 : llvm::Monotonic,
1440 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001441 // OpenMP, 2.12.6, atomic Construct
1442 // Any atomic construct with a seq_cst clause forces the atomically
1443 // performed operation to include an implicit flush operation without a
1444 // list.
1445 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001446 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001447 switch (CGF.getEvaluationKind(V->getType())) {
1448 case TEK_Scalar:
1449 CGF.EmitStoreOfScalar(
1450 convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
1451 break;
1452 case TEK_Complex:
1453 CGF.EmitStoreOfComplex(
1454 convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
1455 /*isInit=*/false);
1456 break;
1457 case TEK_Aggregate:
1458 llvm_unreachable("Must be a scalar or complex.");
1459 }
1460}
1461
Alexey Bataevb8329262015-02-27 06:33:30 +00001462static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1463 const Expr *X, const Expr *E,
1464 SourceLocation Loc) {
1465 // x = expr;
1466 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
1467 LValue XLValue = CGF.EmitLValue(X);
1468 RValue ExprRValue = CGF.EmitAnyExpr(E);
1469 if (XLValue.isGlobalReg())
1470 CGF.EmitStoreThroughGlobalRegLValue(ExprRValue, XLValue);
1471 else
1472 CGF.EmitAtomicStore(ExprRValue, XLValue,
1473 IsSeqCst ? llvm::SequentiallyConsistent
1474 : llvm::Monotonic,
1475 XLValue.isVolatile(), /*IsInit=*/false);
1476 // OpenMP, 2.12.6, atomic Construct
1477 // Any atomic construct with a seq_cst clause forces the atomically
1478 // performed operation to include an implicit flush operation without a
1479 // list.
1480 if (IsSeqCst)
1481 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1482}
1483
Benjamin Kramer5df7c1a2015-04-18 10:00:10 +00001484static bool emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update,
1485 BinaryOperatorKind BO, llvm::AtomicOrdering AO,
1486 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001487 auto &Context = CGF.CGM.getContext();
1488 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001489 // expression is simple and atomic is allowed for the given type for the
1490 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001491 if (BO == BO_Comma || !Update.isScalar() ||
1492 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1493 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1494 (Update.getScalarVal()->getType() !=
1495 X.getAddress()->getType()->getPointerElementType())) ||
1496 !Context.getTargetInfo().hasBuiltinAtomic(
1497 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
1498 return false;
1499
1500 llvm::AtomicRMWInst::BinOp RMWOp;
1501 switch (BO) {
1502 case BO_Add:
1503 RMWOp = llvm::AtomicRMWInst::Add;
1504 break;
1505 case BO_Sub:
1506 if (!IsXLHSInRHSPart)
1507 return false;
1508 RMWOp = llvm::AtomicRMWInst::Sub;
1509 break;
1510 case BO_And:
1511 RMWOp = llvm::AtomicRMWInst::And;
1512 break;
1513 case BO_Or:
1514 RMWOp = llvm::AtomicRMWInst::Or;
1515 break;
1516 case BO_Xor:
1517 RMWOp = llvm::AtomicRMWInst::Xor;
1518 break;
1519 case BO_LT:
1520 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1521 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1522 : llvm::AtomicRMWInst::Max)
1523 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1524 : llvm::AtomicRMWInst::UMax);
1525 break;
1526 case BO_GT:
1527 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1528 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1529 : llvm::AtomicRMWInst::Min)
1530 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1531 : llvm::AtomicRMWInst::UMin);
1532 break;
1533 case BO_Mul:
1534 case BO_Div:
1535 case BO_Rem:
1536 case BO_Shl:
1537 case BO_Shr:
1538 case BO_LAnd:
1539 case BO_LOr:
1540 return false;
1541 case BO_PtrMemD:
1542 case BO_PtrMemI:
1543 case BO_LE:
1544 case BO_GE:
1545 case BO_EQ:
1546 case BO_NE:
1547 case BO_Assign:
1548 case BO_AddAssign:
1549 case BO_SubAssign:
1550 case BO_AndAssign:
1551 case BO_OrAssign:
1552 case BO_XorAssign:
1553 case BO_MulAssign:
1554 case BO_DivAssign:
1555 case BO_RemAssign:
1556 case BO_ShlAssign:
1557 case BO_ShrAssign:
1558 case BO_Comma:
1559 llvm_unreachable("Unsupported atomic update operation");
1560 }
1561 auto *UpdateVal = Update.getScalarVal();
1562 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1563 UpdateVal = CGF.Builder.CreateIntCast(
1564 IC, X.getAddress()->getType()->getPointerElementType(),
1565 X.getType()->hasSignedIntegerRepresentation());
1566 }
1567 CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1568 return true;
1569}
1570
1571void CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
1572 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1573 llvm::AtomicOrdering AO, SourceLocation Loc,
1574 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1575 // Update expressions are allowed to have the following forms:
1576 // x binop= expr; -> xrval + expr;
1577 // x++, ++x -> xrval + 1;
1578 // x--, --x -> xrval - 1;
1579 // x = x binop expr; -> xrval binop expr
1580 // x = expr Op x; - > expr binop xrval;
1581 if (!emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart)) {
1582 if (X.isGlobalReg()) {
1583 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1584 // 'xrval'.
1585 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1586 } else {
1587 // Perform compare-and-swap procedure.
1588 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001589 }
1590 }
Alexey Bataevb4505a72015-03-30 05:20:59 +00001591}
1592
1593static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1594 const Expr *X, const Expr *E,
1595 const Expr *UE, bool IsXLHSInRHSPart,
1596 SourceLocation Loc) {
1597 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1598 "Update expr in 'atomic update' must be a binary operator.");
1599 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1600 // Update expressions are allowed to have the following forms:
1601 // x binop= expr; -> xrval + expr;
1602 // x++, ++x -> xrval + 1;
1603 // x--, --x -> xrval - 1;
1604 // x = x binop expr; -> xrval binop expr
1605 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001606 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001607 LValue XLValue = CGF.EmitLValue(X);
1608 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001609 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001610 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1611 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1612 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1613 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1614 auto Gen =
1615 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1616 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1617 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1618 return CGF.EmitAnyExpr(UE);
1619 };
1620 CGF.EmitOMPAtomicSimpleUpdateExpr(XLValue, ExprRValue, BOUE->getOpcode(),
1621 IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001622 // OpenMP, 2.12.6, atomic Construct
1623 // Any atomic construct with a seq_cst clause forces the atomically
1624 // performed operation to include an implicit flush operation without a
1625 // list.
1626 if (IsSeqCst)
1627 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1628}
1629
Alexey Bataevb57056f2015-01-22 06:17:56 +00001630static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
1631 bool IsSeqCst, const Expr *X, const Expr *V,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001632 const Expr *E, const Expr *UE,
1633 bool IsXLHSInRHSPart, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001634 switch (Kind) {
1635 case OMPC_read:
1636 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1637 break;
1638 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001639 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1640 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001641 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001642 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001643 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1644 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001645 case OMPC_capture:
1646 llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
1647 case OMPC_if:
1648 case OMPC_final:
1649 case OMPC_num_threads:
1650 case OMPC_private:
1651 case OMPC_firstprivate:
1652 case OMPC_lastprivate:
1653 case OMPC_reduction:
1654 case OMPC_safelen:
1655 case OMPC_collapse:
1656 case OMPC_default:
1657 case OMPC_seq_cst:
1658 case OMPC_shared:
1659 case OMPC_linear:
1660 case OMPC_aligned:
1661 case OMPC_copyin:
1662 case OMPC_copyprivate:
1663 case OMPC_flush:
1664 case OMPC_proc_bind:
1665 case OMPC_schedule:
1666 case OMPC_ordered:
1667 case OMPC_nowait:
1668 case OMPC_untied:
1669 case OMPC_threadprivate:
1670 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001671 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1672 }
1673}
1674
1675void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1676 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1677 OpenMPClauseKind Kind = OMPC_unknown;
1678 for (auto *C : S.clauses()) {
1679 // Find first clause (skip seq_cst clause, if it is first).
1680 if (C->getClauseKind() != OMPC_seq_cst) {
1681 Kind = C->getClauseKind();
1682 break;
1683 }
1684 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001685
1686 const auto *CS =
1687 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
1688 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
1689 enterFullExpression(EWC);
Alexey Bataev10fec572015-03-11 04:48:56 +00001690
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001691 LexicalScope Scope(*this, S.getSourceRange());
1692 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
1693 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
1694 S.getUpdateExpr(), S.isXLHSInRHSPart(), S.getLocStart());
1695 };
1696 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001697}
1698
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001699void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1700 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1701}
1702
Alexey Bataev13314bf2014-10-09 04:18:56 +00001703void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1704 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1705}
1706