blob: 21b1bcb9d3a9ec9b18421effd30ab10f043da28c [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();
Alexey Bataev53223c92015-05-07 04:25:17 +0000889 // Generate !llvm.loop.parallel metadata for loads and stores for loops with
890 // dynamic/guided scheduling and without ordered clause.
891 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
892 ScheduleKind == OMPC_SCHEDULE_guided) &&
893 !DynamicWithOrderedClause);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000894 EmitOMPInnerLoop(
895 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
896 S.getInc(),
897 [&S](CodeGenFunction &CGF) {
898 CGF.EmitOMPLoopBody(S);
899 CGF.EmitStopPoint(&S);
900 },
901 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
902 if (DynamicWithOrderedClause) {
903 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
904 CGF, Loc, IVSize, IVSigned);
905 }
906 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000907
908 EmitBlock(Continue.getBlock());
909 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 if (!Dynamic) {
911 // Emit "LB = LB + Stride", "UB = UB + Stride".
912 EmitIgnoredExpr(S.getNextLowerBound());
913 EmitIgnoredExpr(S.getNextUpperBound());
914 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000915
916 EmitBranch(CondBlock);
917 LoopStack.pop();
918 // Emit the fall-through block.
919 EmitBlock(LoopExit.getBlock());
920
921 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000922 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000923 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000924}
925
Alexander Musmanc6388682014-12-15 07:07:06 +0000926/// \brief Emit a helper variable and return corresponding lvalue.
927static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
928 const DeclRefExpr *Helper) {
929 auto VDecl = cast<VarDecl>(Helper->getDecl());
930 CGF.EmitVarDecl(*VDecl);
931 return CGF.EmitLValue(Helper);
932}
933
Alexey Bataev38e89532015-04-16 04:54:05 +0000934bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000935 // Emit the loop iteration variable.
936 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
937 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
938 EmitVarDecl(*IVDecl);
939
940 // Emit the iterations count variable.
941 // If it is not a variable, Sema decided to calculate iterations count on each
942 // iteration (e.g., it is foldable into a constant).
943 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
944 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
945 // Emit calculation of the iterations count.
946 EmitIgnoredExpr(S.getCalcLastIteration());
947 }
948
949 auto &RT = CGM.getOpenMPRuntime();
950
Alexey Bataev38e89532015-04-16 04:54:05 +0000951 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +0000952 // Check pre-condition.
953 {
954 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +0000955 // If the condition constant folds and can be elided, avoid emitting the
956 // whole loop.
957 bool CondConstant;
958 llvm::BasicBlock *ContBlock = nullptr;
959 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
960 if (!CondConstant)
961 return false;
962 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000963 auto *ThenBlock = createBasicBlock("omp.precond.then");
964 ContBlock = createBasicBlock("omp.precond.end");
965 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +0000966 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000967 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000968 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000969 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000970 // Emit 'then' code.
971 {
972 // Emit helper vars inits.
973 LValue LB =
974 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
975 LValue UB =
976 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
977 LValue ST =
978 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
979 LValue IL =
980 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
981
982 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000983 if (EmitOMPFirstprivateClause(S, LoopScope)) {
984 // Emit implicit barrier to synchronize threads and avoid data races on
985 // initialization of firstprivate variables.
986 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
987 OMPD_unknown);
988 }
Alexey Bataev50a64582015-04-22 12:24:45 +0000989 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +0000990 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +0000991 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +0000992 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +0000993 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +0000994
995 // Detect the loop schedule kind and chunk.
996 auto ScheduleKind = OMPC_SCHEDULE_unknown;
997 llvm::Value *Chunk = nullptr;
998 if (auto C = cast_or_null<OMPScheduleClause>(
999 S.getSingleClause(OMPC_schedule))) {
1000 ScheduleKind = C->getScheduleKind();
1001 if (auto Ch = C->getChunkSize()) {
1002 Chunk = EmitScalarExpr(Ch);
1003 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1004 S.getIterationVariable()->getType());
1005 }
1006 }
1007 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1008 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1009 if (RT.isStaticNonchunked(ScheduleKind,
1010 /* Chunked */ Chunk != nullptr)) {
1011 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1012 // When no chunk_size is specified, the iteration space is divided into
1013 // chunks that are approximately equal in size, and at most one chunk is
1014 // distributed to each thread. Note that the size of the chunks is
1015 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001016 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1017 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1018 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001019 // UB = min(UB, GlobalUB);
1020 EmitIgnoredExpr(S.getEnsureUpperBound());
1021 // IV = LB;
1022 EmitIgnoredExpr(S.getInit());
1023 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001024 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1025 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001026 [&S](CodeGenFunction &CGF) {
1027 CGF.EmitOMPLoopBody(S);
1028 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001029 },
1030 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001031 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001032 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001033 } else {
1034 // Emit the outer loop, which requests its work chunk [LB..UB] from
1035 // runtime and runs the inner loop to process it.
1036 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1037 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1038 Chunk);
1039 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001040 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001041 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1042 if (HasLastprivateClause)
1043 EmitOMPLastprivateClauseFinal(
1044 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001045 }
1046 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001047 if (ContBlock) {
1048 EmitBranch(ContBlock);
1049 EmitBlock(ContBlock, true);
1050 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001051 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001052 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001053}
1054
1055void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001056 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001057 bool HasLastprivates = false;
1058 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1059 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1060 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001061 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001062
1063 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001064 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001065 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1066 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001067}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001068
Alexander Musmanf82886e2014-09-18 05:12:34 +00001069void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1070 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1071}
1072
Alexey Bataev2df54a02015-03-12 08:53:29 +00001073static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1074 const Twine &Name,
1075 llvm::Value *Init = nullptr) {
1076 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1077 if (Init)
1078 CGF.EmitScalarInit(Init, LVal);
1079 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001080}
1081
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001082static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1083 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001084 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1085 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1086 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001087 bool HasLastprivates = false;
1088 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001089 auto &C = CGF.CGM.getContext();
1090 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1091 // Emit helper vars inits.
1092 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1093 CGF.Builder.getInt32(0));
1094 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1095 LValue UB =
1096 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1097 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1098 CGF.Builder.getInt32(1));
1099 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1100 CGF.Builder.getInt32(0));
1101 // Loop counter.
1102 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1103 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001104 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001105 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001106 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001107 // Generate condition for loop.
1108 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1109 OK_Ordinary, S.getLocStart(),
1110 /*fpContractable=*/false);
1111 // Increment for loop counter.
1112 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1113 OK_Ordinary, S.getLocStart());
1114 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1115 // Iterate through all sections and emit a switch construct:
1116 // switch (IV) {
1117 // case 0:
1118 // <SectionStmt[0]>;
1119 // break;
1120 // ...
1121 // case <NumSection> - 1:
1122 // <SectionStmt[<NumSection> - 1]>;
1123 // break;
1124 // }
1125 // .omp.sections.exit:
1126 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1127 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1128 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1129 CS->size());
1130 unsigned CaseNumber = 0;
1131 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1132 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1133 CGF.EmitBlock(CaseBB);
1134 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1135 CGF.EmitStmt(*C);
1136 CGF.EmitBranch(ExitBB);
1137 }
1138 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1139 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001140
1141 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1142 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1143 // Emit implicit barrier to synchronize threads and avoid data races on
1144 // initialization of firstprivate variables.
1145 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1146 OMPD_unknown);
1147 }
Alexey Bataev73870832015-04-27 04:12:12 +00001148 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001149 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001150 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001151 (void)LoopScope.Privatize();
1152
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001153 // Emit static non-chunked loop.
1154 CGF.CGM.getOpenMPRuntime().emitForInit(
1155 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1156 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1157 ST.getAddress());
1158 // UB = min(UB, GlobalUB);
1159 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1160 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1161 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1162 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1163 // IV = LB;
1164 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1165 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001166 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1167 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001168 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001169 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001170 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001171
1172 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1173 if (HasLastprivates)
1174 CGF.EmitOMPLastprivateClauseFinal(
1175 S, CGF.Builder.CreateIsNotNull(
1176 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001177 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001178
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001179 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001180 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1181 // clause. Otherwise the barrier will be generated by the codegen for the
1182 // directive.
1183 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1184 // Emit implicit barrier to synchronize threads and avoid data races on
1185 // initialization of firstprivate variables.
1186 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1187 OMPD_unknown);
1188 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001189 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.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001193 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001194 // No need to generate reductions for sections with single section region, we
1195 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001196 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001197 // No need to generate lastprivates for sections with single section region,
1198 // we can use original shared variable for all calculations with barrier at
1199 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001200 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001201 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1202 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1203 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001204 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001205 (void)SingleScope.Privatize();
1206
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001207 CGF.EmitStmt(Stmt);
1208 CGF.EnsureInsertPoint();
1209 };
1210 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1211 llvm::None, llvm::None,
1212 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001213 // Emit barrier for firstprivates, lastprivates or reductions only if
1214 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1215 // generated by the codegen for the directive.
1216 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1217 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001218 // Emit implicit barrier to synchronize threads and avoid data races on
1219 // initialization of firstprivate variables.
1220 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1221 OMPD_unknown);
1222 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001223 return OMPD_single;
1224}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001225
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001226void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1227 LexicalScope Scope(*this, S.getSourceRange());
1228 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001229 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001230 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001231 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001232 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001233}
1234
1235void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001236 LexicalScope Scope(*this, S.getSourceRange());
1237 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1238 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1239 CGF.EnsureInsertPoint();
1240 };
1241 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001242}
1243
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001244void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001245 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001246 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001247 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001248 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001249 // Check if there are any 'copyprivate' clauses associated with this
1250 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001251 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001252 // Build a list of copyprivate variables along with helper expressions
1253 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001254 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001255 auto *C = cast<OMPCopyprivateClause>(*I);
1256 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001257 DestExprs.append(C->destination_exprs().begin(),
1258 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001259 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001260 AssignmentOps.append(C->assignment_ops().begin(),
1261 C->assignment_ops().end());
1262 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001264 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001265 bool HasFirstprivates;
1266 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1267 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1268 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001269 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001270 (void)SingleScope.Privatize();
1271
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1273 CGF.EnsureInsertPoint();
1274 };
1275 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001276 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001277 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001278 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1279 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1280 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1281 CopyprivateVars.empty()) {
1282 CGM.getOpenMPRuntime().emitBarrierCall(
1283 *this, S.getLocStart(),
1284 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001285 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001286}
1287
Alexey Bataev8d690652014-12-04 07:23:53 +00001288void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001289 LexicalScope Scope(*this, S.getSourceRange());
1290 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1291 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1292 CGF.EnsureInsertPoint();
1293 };
1294 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001295}
1296
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001297void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001298 LexicalScope Scope(*this, S.getSourceRange());
1299 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1300 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1301 CGF.EnsureInsertPoint();
1302 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001303 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001304 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001305}
1306
Alexey Bataev671605e2015-04-13 05:28:11 +00001307void CodeGenFunction::EmitOMPParallelForDirective(
1308 const OMPParallelForDirective &S) {
1309 // Emit directive as a combined directive that consists of two implicit
1310 // directives: 'parallel' with 'for' directive.
1311 LexicalScope Scope(*this, S.getSourceRange());
1312 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1313 CGF.EmitOMPWorksharingLoop(S);
1314 // Emit implicit barrier at the end of parallel region, but this barrier
1315 // is at the end of 'for' directive, so emit it as the implicit barrier for
1316 // this 'for' directive.
1317 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1318 OMPD_parallel);
1319 };
1320 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001321}
1322
Alexander Musmane4e893b2014-09-23 09:33:00 +00001323void CodeGenFunction::EmitOMPParallelForSimdDirective(
1324 const OMPParallelForSimdDirective &) {
1325 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1326}
1327
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001328void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001329 const OMPParallelSectionsDirective &S) {
1330 // Emit directive as a combined directive that consists of two implicit
1331 // directives: 'parallel' with 'sections' directive.
1332 LexicalScope Scope(*this, S.getSourceRange());
1333 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1334 (void)emitSections(CGF, S);
1335 // Emit implicit barrier at the end of parallel region.
1336 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1337 OMPD_parallel);
1338 };
1339 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001340}
1341
Alexey Bataev62b63b12015-03-10 07:28:44 +00001342void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1343 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001344 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001345 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1346 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1347 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001348 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001349 // The first function argument for tasks is a thread id, the second one is a
1350 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1352 if (*PartId) {
1353 // TODO: emit code for untied tasks.
1354 }
1355 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1356 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001357 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001358 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001359 // Check if we should emit tied or untied task.
1360 bool Tied = !S.getSingleClause(OMPC_untied);
1361 // Check if the task is final
1362 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1363 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1364 // If the condition constant folds and can be elided, try to avoid emitting
1365 // the condition and the dead arm of the if/else.
1366 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1367 bool CondConstant;
1368 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1369 Final.setInt(CondConstant);
1370 else
1371 Final.setPointer(EvaluateExprAsBool(Cond));
1372 } else {
1373 // By default the task is not final.
1374 Final.setInt(/*IntVal=*/false);
1375 }
1376 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001377 const Expr *IfCond = nullptr;
1378 if (auto C = S.getSingleClause(OMPC_if)) {
1379 IfCond = cast<OMPIfClause>(C)->getCondition();
1380 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001381 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001382 // Get list of private variables.
1383 llvm::SmallVector<const Expr *, 8> Privates;
1384 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001385 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1386 auto *C = cast<OMPPrivateClause>(*I);
1387 auto IRef = C->varlist_begin();
1388 for (auto *IInit : C->private_copies()) {
1389 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1390 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1391 Privates.push_back(*IRef);
1392 PrivateCopies.push_back(IInit);
1393 }
1394 ++IRef;
1395 }
1396 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001397 EmittedAsPrivate.clear();
1398 // Get list of firstprivate variables.
1399 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1400 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1401 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1402 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1403 auto *C = cast<OMPFirstprivateClause>(*I);
1404 auto IRef = C->varlist_begin();
1405 auto IElemInitRef = C->inits().begin();
1406 for (auto *IInit : C->private_copies()) {
1407 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1408 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1409 FirstprivateVars.push_back(*IRef);
1410 FirstprivateCopies.push_back(IInit);
1411 FirstprivateInits.push_back(*IElemInitRef);
1412 }
1413 ++IRef, ++IElemInitRef;
1414 }
1415 }
1416 CGM.getOpenMPRuntime().emitTaskCall(
1417 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
1418 CapturedStruct, IfCond, Privates, PrivateCopies, FirstprivateVars,
1419 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001420}
1421
Alexey Bataev9f797f32015-02-05 05:57:51 +00001422void CodeGenFunction::EmitOMPTaskyieldDirective(
1423 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001424 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001425}
1426
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001427void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001428 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001429}
1430
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001431void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1432 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001433}
1434
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001435void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001436 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1437 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1438 auto FlushClause = cast<OMPFlushClause>(C);
1439 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1440 FlushClause->varlist_end());
1441 }
1442 return llvm::None;
1443 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001444}
1445
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001446void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1447 LexicalScope Scope(*this, S.getSourceRange());
1448 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1449 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1450 CGF.EnsureInsertPoint();
1451 };
1452 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001453}
1454
Alexey Bataevb57056f2015-01-22 06:17:56 +00001455static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1456 QualType SrcType, QualType DestType) {
1457 assert(CGF.hasScalarEvaluationKind(DestType) &&
1458 "DestType must have scalar evaluation kind.");
1459 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1460 return Val.isScalar()
1461 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1462 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1463 DestType);
1464}
1465
1466static CodeGenFunction::ComplexPairTy
1467convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1468 QualType DestType) {
1469 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1470 "DestType must have complex evaluation kind.");
1471 CodeGenFunction::ComplexPairTy ComplexVal;
1472 if (Val.isScalar()) {
1473 // Convert the input element to the element type of the complex.
1474 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1475 auto ScalarVal =
1476 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1477 ComplexVal = CodeGenFunction::ComplexPairTy(
1478 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1479 } else {
1480 assert(Val.isComplex() && "Must be a scalar or complex.");
1481 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1482 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1483 ComplexVal.first = CGF.EmitScalarConversion(
1484 Val.getComplexVal().first, SrcElementType, DestElementType);
1485 ComplexVal.second = CGF.EmitScalarConversion(
1486 Val.getComplexVal().second, SrcElementType, DestElementType);
1487 }
1488 return ComplexVal;
1489}
1490
Alexey Bataev5e018f92015-04-23 06:35:10 +00001491static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1492 LValue LVal, RValue RVal) {
1493 if (LVal.isGlobalReg()) {
1494 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1495 } else {
1496 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1497 : llvm::Monotonic,
1498 LVal.isVolatile(), /*IsInit=*/false);
1499 }
1500}
1501
1502static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1503 QualType RValTy) {
1504 switch (CGF.getEvaluationKind(LVal.getType())) {
1505 case TEK_Scalar:
1506 CGF.EmitStoreThroughLValue(
1507 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1508 LVal);
1509 break;
1510 case TEK_Complex:
1511 CGF.EmitStoreOfComplex(
1512 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1513 /*isInit=*/false);
1514 break;
1515 case TEK_Aggregate:
1516 llvm_unreachable("Must be a scalar or complex.");
1517 }
1518}
1519
Alexey Bataevb57056f2015-01-22 06:17:56 +00001520static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1521 const Expr *X, const Expr *V,
1522 SourceLocation Loc) {
1523 // v = x;
1524 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1525 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1526 LValue XLValue = CGF.EmitLValue(X);
1527 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001528 RValue Res = XLValue.isGlobalReg()
1529 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1530 : CGF.EmitAtomicLoad(XLValue, Loc,
1531 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001532 : llvm::Monotonic,
1533 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001534 // OpenMP, 2.12.6, atomic Construct
1535 // Any atomic construct with a seq_cst clause forces the atomically
1536 // performed operation to include an implicit flush operation without a
1537 // list.
1538 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001539 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001540 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001541}
1542
Alexey Bataevb8329262015-02-27 06:33:30 +00001543static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1544 const Expr *X, const Expr *E,
1545 SourceLocation Loc) {
1546 // x = expr;
1547 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001548 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001549 // OpenMP, 2.12.6, atomic Construct
1550 // Any atomic construct with a seq_cst clause forces the atomically
1551 // performed operation to include an implicit flush operation without a
1552 // list.
1553 if (IsSeqCst)
1554 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1555}
1556
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001557static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1558 RValue Update,
1559 BinaryOperatorKind BO,
1560 llvm::AtomicOrdering AO,
1561 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001562 auto &Context = CGF.CGM.getContext();
1563 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001564 // expression is simple and atomic is allowed for the given type for the
1565 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001566 if (BO == BO_Comma || !Update.isScalar() ||
1567 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1568 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1569 (Update.getScalarVal()->getType() !=
1570 X.getAddress()->getType()->getPointerElementType())) ||
1571 !Context.getTargetInfo().hasBuiltinAtomic(
1572 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001573 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001574
1575 llvm::AtomicRMWInst::BinOp RMWOp;
1576 switch (BO) {
1577 case BO_Add:
1578 RMWOp = llvm::AtomicRMWInst::Add;
1579 break;
1580 case BO_Sub:
1581 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001582 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001583 RMWOp = llvm::AtomicRMWInst::Sub;
1584 break;
1585 case BO_And:
1586 RMWOp = llvm::AtomicRMWInst::And;
1587 break;
1588 case BO_Or:
1589 RMWOp = llvm::AtomicRMWInst::Or;
1590 break;
1591 case BO_Xor:
1592 RMWOp = llvm::AtomicRMWInst::Xor;
1593 break;
1594 case BO_LT:
1595 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1596 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1597 : llvm::AtomicRMWInst::Max)
1598 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1599 : llvm::AtomicRMWInst::UMax);
1600 break;
1601 case BO_GT:
1602 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1603 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1604 : llvm::AtomicRMWInst::Min)
1605 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1606 : llvm::AtomicRMWInst::UMin);
1607 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001608 case BO_Assign:
1609 RMWOp = llvm::AtomicRMWInst::Xchg;
1610 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001611 case BO_Mul:
1612 case BO_Div:
1613 case BO_Rem:
1614 case BO_Shl:
1615 case BO_Shr:
1616 case BO_LAnd:
1617 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001618 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001619 case BO_PtrMemD:
1620 case BO_PtrMemI:
1621 case BO_LE:
1622 case BO_GE:
1623 case BO_EQ:
1624 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001625 case BO_AddAssign:
1626 case BO_SubAssign:
1627 case BO_AndAssign:
1628 case BO_OrAssign:
1629 case BO_XorAssign:
1630 case BO_MulAssign:
1631 case BO_DivAssign:
1632 case BO_RemAssign:
1633 case BO_ShlAssign:
1634 case BO_ShrAssign:
1635 case BO_Comma:
1636 llvm_unreachable("Unsupported atomic update operation");
1637 }
1638 auto *UpdateVal = Update.getScalarVal();
1639 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1640 UpdateVal = CGF.Builder.CreateIntCast(
1641 IC, X.getAddress()->getType()->getPointerElementType(),
1642 X.getType()->hasSignedIntegerRepresentation());
1643 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001644 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1645 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001646}
1647
Alexey Bataev5e018f92015-04-23 06:35:10 +00001648std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001649 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1650 llvm::AtomicOrdering AO, SourceLocation Loc,
1651 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1652 // Update expressions are allowed to have the following forms:
1653 // x binop= expr; -> xrval + expr;
1654 // x++, ++x -> xrval + 1;
1655 // x--, --x -> xrval - 1;
1656 // x = x binop expr; -> xrval binop expr
1657 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001658 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1659 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001660 if (X.isGlobalReg()) {
1661 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1662 // 'xrval'.
1663 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1664 } else {
1665 // Perform compare-and-swap procedure.
1666 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001667 }
1668 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001669 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001670}
1671
1672static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1673 const Expr *X, const Expr *E,
1674 const Expr *UE, bool IsXLHSInRHSPart,
1675 SourceLocation Loc) {
1676 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1677 "Update expr in 'atomic update' must be a binary operator.");
1678 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1679 // Update expressions are allowed to have the following forms:
1680 // x binop= expr; -> xrval + expr;
1681 // x++, ++x -> xrval + 1;
1682 // x--, --x -> xrval - 1;
1683 // x = x binop expr; -> xrval binop expr
1684 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001685 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001686 LValue XLValue = CGF.EmitLValue(X);
1687 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001688 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001689 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1690 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1691 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1692 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1693 auto Gen =
1694 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1695 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1696 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1697 return CGF.EmitAnyExpr(UE);
1698 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001699 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1700 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1701 // OpenMP, 2.12.6, atomic Construct
1702 // Any atomic construct with a seq_cst clause forces the atomically
1703 // performed operation to include an implicit flush operation without a
1704 // list.
1705 if (IsSeqCst)
1706 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1707}
1708
1709static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1710 QualType SourceType, QualType ResType) {
1711 switch (CGF.getEvaluationKind(ResType)) {
1712 case TEK_Scalar:
1713 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1714 case TEK_Complex: {
1715 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1716 return RValue::getComplex(Res.first, Res.second);
1717 }
1718 case TEK_Aggregate:
1719 break;
1720 }
1721 llvm_unreachable("Must be a scalar or complex.");
1722}
1723
1724static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1725 bool IsPostfixUpdate, const Expr *V,
1726 const Expr *X, const Expr *E,
1727 const Expr *UE, bool IsXLHSInRHSPart,
1728 SourceLocation Loc) {
1729 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1730 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1731 RValue NewVVal;
1732 LValue VLValue = CGF.EmitLValue(V);
1733 LValue XLValue = CGF.EmitLValue(X);
1734 RValue ExprRValue = CGF.EmitAnyExpr(E);
1735 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1736 QualType NewVValType;
1737 if (UE) {
1738 // 'x' is updated with some additional value.
1739 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1740 "Update expr in 'atomic capture' must be a binary operator.");
1741 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1742 // Update expressions are allowed to have the following forms:
1743 // x binop= expr; -> xrval + expr;
1744 // x++, ++x -> xrval + 1;
1745 // x--, --x -> xrval - 1;
1746 // x = x binop expr; -> xrval binop expr
1747 // x = expr Op x; - > expr binop xrval;
1748 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1749 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1750 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1751 NewVValType = XRValExpr->getType();
1752 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1753 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1754 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1755 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1756 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1757 RValue Res = CGF.EmitAnyExpr(UE);
1758 NewVVal = IsPostfixUpdate ? XRValue : Res;
1759 return Res;
1760 };
1761 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1762 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1763 if (Res.first) {
1764 // 'atomicrmw' instruction was generated.
1765 if (IsPostfixUpdate) {
1766 // Use old value from 'atomicrmw'.
1767 NewVVal = Res.second;
1768 } else {
1769 // 'atomicrmw' does not provide new value, so evaluate it using old
1770 // value of 'x'.
1771 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1772 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1773 NewVVal = CGF.EmitAnyExpr(UE);
1774 }
1775 }
1776 } else {
1777 // 'x' is simply rewritten with some 'expr'.
1778 NewVValType = X->getType().getNonReferenceType();
1779 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1780 X->getType().getNonReferenceType());
1781 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1782 NewVVal = XRValue;
1783 return ExprRValue;
1784 };
1785 // Try to perform atomicrmw xchg, otherwise simple exchange.
1786 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1787 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1788 Loc, Gen);
1789 if (Res.first) {
1790 // 'atomicrmw' instruction was generated.
1791 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1792 }
1793 }
1794 // Emit post-update store to 'v' of old/new 'x' value.
1795 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001796 // OpenMP, 2.12.6, atomic Construct
1797 // Any atomic construct with a seq_cst clause forces the atomically
1798 // performed operation to include an implicit flush operation without a
1799 // list.
1800 if (IsSeqCst)
1801 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1802}
1803
Alexey Bataevb57056f2015-01-22 06:17:56 +00001804static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001805 bool IsSeqCst, bool IsPostfixUpdate,
1806 const Expr *X, const Expr *V, const Expr *E,
1807 const Expr *UE, bool IsXLHSInRHSPart,
1808 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001809 switch (Kind) {
1810 case OMPC_read:
1811 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1812 break;
1813 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001814 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1815 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001816 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001817 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001818 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1819 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001820 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001821 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1822 IsXLHSInRHSPart, Loc);
1823 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001824 case OMPC_if:
1825 case OMPC_final:
1826 case OMPC_num_threads:
1827 case OMPC_private:
1828 case OMPC_firstprivate:
1829 case OMPC_lastprivate:
1830 case OMPC_reduction:
1831 case OMPC_safelen:
1832 case OMPC_collapse:
1833 case OMPC_default:
1834 case OMPC_seq_cst:
1835 case OMPC_shared:
1836 case OMPC_linear:
1837 case OMPC_aligned:
1838 case OMPC_copyin:
1839 case OMPC_copyprivate:
1840 case OMPC_flush:
1841 case OMPC_proc_bind:
1842 case OMPC_schedule:
1843 case OMPC_ordered:
1844 case OMPC_nowait:
1845 case OMPC_untied:
1846 case OMPC_threadprivate:
1847 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001848 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1849 }
1850}
1851
1852void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1853 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1854 OpenMPClauseKind Kind = OMPC_unknown;
1855 for (auto *C : S.clauses()) {
1856 // Find first clause (skip seq_cst clause, if it is first).
1857 if (C->getClauseKind() != OMPC_seq_cst) {
1858 Kind = C->getClauseKind();
1859 break;
1860 }
1861 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001862
1863 const auto *CS =
1864 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001865 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001866 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001867 }
1868 // Processing for statements under 'atomic capture'.
1869 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1870 for (const auto *C : Compound->body()) {
1871 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1872 enterFullExpression(EWC);
1873 }
1874 }
1875 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001876
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001877 LexicalScope Scope(*this, S.getSourceRange());
1878 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001879 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1880 S.getV(), S.getExpr(), S.getUpdateExpr(),
1881 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001882 };
1883 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001884}
1885
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001886void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1887 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1888}
1889
Alexey Bataev13314bf2014-10-09 04:18:56 +00001890void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1891 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1892}