blob: 9a25f2eed92bfb3656c26ad20abe6a52de87fa0f [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 Bataevd74d0602014-10-13 06:02:40 +000026/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
27/// function. Here is the logic:
28/// if (Cond) {
29/// CodeGen(true);
30/// } else {
31/// CodeGen(false);
32/// }
33static void EmitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
34 const std::function<void(bool)> &CodeGen) {
35 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
36
37 // If the condition constant folds and can be elided, try to avoid emitting
38 // the condition and the dead arm of the if/else.
39 bool CondConstant;
40 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
41 CodeGen(CondConstant);
42 return;
43 }
44
45 // Otherwise, the condition did not fold, or we couldn't elide it. Just
46 // emit the conditional branch.
47 auto ThenBlock = CGF.createBasicBlock(/*name*/ "omp_if.then");
48 auto ElseBlock = CGF.createBasicBlock(/*name*/ "omp_if.else");
49 auto ContBlock = CGF.createBasicBlock(/*name*/ "omp_if.end");
50 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount*/ 0);
51
52 // Emit the 'then' code.
53 CGF.EmitBlock(ThenBlock);
54 CodeGen(/*ThenBlock*/ true);
55 CGF.EmitBranch(ContBlock);
56 // Emit the 'else' code if present.
57 {
58 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +000059 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd74d0602014-10-13 06:02:40 +000060 CGF.EmitBlock(ElseBlock);
61 }
62 CodeGen(/*ThenBlock*/ false);
63 {
64 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +000065 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd74d0602014-10-13 06:02:40 +000066 CGF.EmitBranch(ContBlock);
67 }
68 // Emit the continuation block for code after the if.
69 CGF.EmitBlock(ContBlock, /*IsFinished*/ true);
70}
71
Alexey Bataev420d45b2015-04-14 05:11:24 +000072void CodeGenFunction::EmitOMPAggregateAssign(
73 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
74 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) {
75 // Perform element-by-element initialization.
76 QualType ElementTy;
77 auto SrcBegin = SrcAddr;
78 auto DestBegin = DestAddr;
79 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
80 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
81 // Cast from pointer to array type to pointer to single element.
82 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin,
83 DestBegin->getType());
84 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
85 // The basic structure here is a while-do loop.
86 auto BodyBB = createBasicBlock("omp.arraycpy.body");
87 auto DoneBB = createBasicBlock("omp.arraycpy.done");
88 auto IsEmpty =
89 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
90 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000091
Alexey Bataev420d45b2015-04-14 05:11:24 +000092 // Enter the loop body, making that address the current address.
93 auto EntryBB = Builder.GetInsertBlock();
94 EmitBlock(BodyBB);
95 auto SrcElementCurrent =
96 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
97 SrcElementCurrent->addIncoming(SrcBegin, EntryBB);
98 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2,
99 "omp.arraycpy.destElementPast");
100 DestElementCurrent->addIncoming(DestBegin, EntryBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000101
Alexey Bataev420d45b2015-04-14 05:11:24 +0000102 // Emit copy.
103 CopyGen(DestElementCurrent, SrcElementCurrent);
104
105 // Shift the address forward by one element.
106 auto DestElementNext = Builder.CreateConstGEP1_32(
107 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element");
108 auto SrcElementNext = Builder.CreateConstGEP1_32(
109 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element");
110 // Check whether we've reached the end.
111 auto Done =
112 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
113 Builder.CreateCondBr(Done, DoneBB, BodyBB);
114 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock());
115 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock());
116
117 // Done.
118 EmitBlock(DoneBB, /*IsFinished=*/true);
119}
120
121void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF,
122 QualType OriginalType, llvm::Value *DestAddr,
123 llvm::Value *SrcAddr, const VarDecl *DestVD,
124 const VarDecl *SrcVD, const Expr *Copy) {
125 if (OriginalType->isArrayType()) {
126 auto *BO = dyn_cast<BinaryOperator>(Copy);
127 if (BO && BO->getOpcode() == BO_Assign) {
128 // Perform simple memcpy for simple copying.
129 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
130 } else {
131 // For arrays with complex element types perform element by element
132 // copying.
133 CGF.EmitOMPAggregateAssign(
134 DestAddr, SrcAddr, OriginalType,
135 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement,
136 llvm::Value *SrcElement) {
137 // Working with the single array element, so have to remap
138 // destination and source variables to corresponding array
139 // elements.
140 CodeGenFunction::OMPPrivateScope Remap(CGF);
141 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{
142 return DestElement;
143 });
144 Remap.addPrivate(
145 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; });
146 (void)Remap.Privatize();
147 CGF.EmitIgnoredExpr(Copy);
148 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000149 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000150 } else {
151 // Remap pseudo source variable to private copy.
152 CodeGenFunction::OMPPrivateScope Remap(CGF);
153 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; });
154 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; });
155 (void)Remap.Privatize();
156 // Emit copying of the whole variable.
157 CGF.EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000158 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000159}
160
161void CodeGenFunction::EmitOMPFirstprivateClause(
162 const OMPExecutableDirective &D,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000163 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000164 auto PrivateFilter = [](const OMPClause *C) -> bool {
165 return C->getClauseKind() == OMPC_firstprivate;
166 };
167 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
168 I(D.clauses(), PrivateFilter); I; ++I) {
169 auto *C = cast<OMPFirstprivateClause>(*I);
170 auto IRef = C->varlist_begin();
171 auto InitsRef = C->inits().begin();
172 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000173 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
174 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
175 bool IsRegistered;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000176 if (*InitsRef != nullptr) {
177 // Emit VarDecl with copy init for arrays.
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000178 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000179 LValue Base = MakeNaturalAlignAddrLValue(
180 CapturedStmtInfo->getContextValue(),
181 getContext().getTagDeclType(FD->getParent()));
Alexey Bataev420d45b2015-04-14 05:11:24 +0000182 auto *OriginalAddr = EmitLValueForField(Base, FD).getAddress();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000183 auto VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000184 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000185 auto Emission = EmitAutoVarAlloca(*VD);
186 // Emit initialization of aggregate firstprivate vars.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000187 auto *Init = VD->getInit();
188 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
189 // Perform simple memcpy.
190 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
191 (*IRef)->getType());
192 } else {
193 EmitOMPAggregateAssign(
194 Emission.getAllocatedAddress(), OriginalAddr,
195 (*IRef)->getType(),
196 [this, VDInit, Init](llvm::Value *DestElement,
197 llvm::Value *SrcElement) {
198 // Clean up any temporaries needed by the initialization.
199 RunCleanupsScope InitScope(*this);
200 // Emit initialization for single element.
201 LocalDeclMap[VDInit] = SrcElement;
202 EmitAnyExprToMem(Init, DestElement,
203 Init->getType().getQualifiers(),
204 /*IsInitializer*/ false);
205 LocalDeclMap.erase(VDInit);
206 });
207 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000208 EmitAutoVarCleanups(Emission);
209 return Emission.getAllocatedAddress();
210 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000211 } else
Alexey Bataev420d45b2015-04-14 05:11:24 +0000212 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000213 // Emit private VarDecl with copy init.
214 EmitDecl(*VD);
215 return GetAddrOfLocalVar(VD);
216 });
Alexander Musman7931b982015-03-16 07:14:41 +0000217 assert(IsRegistered && "firstprivate var already registered as private");
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000218 // Silence the warning about unused variable.
219 (void)IsRegistered;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000220 ++IRef, ++InitsRef;
221 }
222 }
223}
224
Alexey Bataev03b340a2014-10-21 03:16:40 +0000225void CodeGenFunction::EmitOMPPrivateClause(
226 const OMPExecutableDirective &D,
227 CodeGenFunction::OMPPrivateScope &PrivateScope) {
228 auto PrivateFilter = [](const OMPClause *C) -> bool {
229 return C->getClauseKind() == OMPC_private;
230 };
231 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
232 I(D.clauses(), PrivateFilter); I; ++I) {
233 auto *C = cast<OMPPrivateClause>(*I);
234 auto IRef = C->varlist_begin();
235 for (auto IInit : C->private_copies()) {
236 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
237 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
238 bool IsRegistered =
239 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value * {
240 // Emit private VarDecl with copy init.
241 EmitDecl(*VD);
242 return GetAddrOfLocalVar(VD);
243 });
Alexander Musman7931b982015-03-16 07:14:41 +0000244 assert(IsRegistered && "private var already registered as private");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000245 // Silence the warning about unused variable.
246 (void)IsRegistered;
247 ++IRef;
248 }
249 }
250}
251
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000252void CodeGenFunction::EmitOMPReductionClauseInit(
253 const OMPExecutableDirective &D,
254 CodeGenFunction::OMPPrivateScope &PrivateScope) {
255 auto ReductionFilter = [](const OMPClause *C) -> bool {
256 return C->getClauseKind() == OMPC_reduction;
257 };
258 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
259 ReductionFilter)> I(D.clauses(), ReductionFilter);
260 I; ++I) {
261 auto *C = cast<OMPReductionClause>(*I);
262 auto ILHS = C->lhs_exprs().begin();
263 auto IRHS = C->rhs_exprs().begin();
264 for (auto IRef : C->varlists()) {
265 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
266 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
267 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
268 // Store the address of the original variable associated with the LHS
269 // implicit variable.
270 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
271 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
272 CapturedStmtInfo->lookup(OrigVD) != nullptr,
273 IRef->getType(), VK_LValue, IRef->getExprLoc());
274 return EmitLValue(&DRE).getAddress();
275 });
276 // Emit reduction copy.
277 bool IsRegistered =
278 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
279 // Emit private VarDecl with reduction init.
280 EmitDecl(*PrivateVD);
281 return GetAddrOfLocalVar(PrivateVD);
282 });
283 assert(IsRegistered && "private var already registered as private");
284 // Silence the warning about unused variable.
285 (void)IsRegistered;
286 ++ILHS, ++IRHS;
287 }
288 }
289}
290
291void CodeGenFunction::EmitOMPReductionClauseFinal(
292 const OMPExecutableDirective &D) {
293 llvm::SmallVector<const Expr *, 8> LHSExprs;
294 llvm::SmallVector<const Expr *, 8> RHSExprs;
295 llvm::SmallVector<const Expr *, 8> ReductionOps;
296 auto ReductionFilter = [](const OMPClause *C) -> bool {
297 return C->getClauseKind() == OMPC_reduction;
298 };
299 bool HasAtLeastOneReduction = false;
300 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
301 ReductionFilter)> I(D.clauses(), ReductionFilter);
302 I; ++I) {
303 HasAtLeastOneReduction = true;
304 auto *C = cast<OMPReductionClause>(*I);
305 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
306 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
307 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
308 }
309 if (HasAtLeastOneReduction) {
310 // Emit nowait reduction if nowait clause is present or directive is a
311 // parallel directive (it always has implicit barrier).
312 CGM.getOpenMPRuntime().emitReduction(
313 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
314 D.getSingleClause(OMPC_nowait) ||
315 isOpenMPParallelDirective(D.getDirectiveKind()));
316 }
317}
318
Alexey Bataevb2059782014-10-13 08:23:51 +0000319/// \brief Emits code for OpenMP parallel directive in the parallel region.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000320static void emitOMPParallelCall(CodeGenFunction &CGF,
321 const OMPExecutableDirective &S,
Alexey Bataevb2059782014-10-13 08:23:51 +0000322 llvm::Value *OutlinedFn,
323 llvm::Value *CapturedStruct) {
324 if (auto C = S.getSingleClause(/*K*/ OMPC_num_threads)) {
325 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
326 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
327 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
328 /*IgnoreResultAssign*/ true);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000329 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Alexey Bataevb2059782014-10-13 08:23:51 +0000330 CGF, NumThreads, NumThreadsClause->getLocStart());
331 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000332 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
333 CapturedStruct);
Alexey Bataevb2059782014-10-13 08:23:51 +0000334}
335
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000336static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
337 const OMPExecutableDirective &S,
338 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000339 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000340 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
341 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
342 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000343 if (auto C = S.getSingleClause(/*K*/ OMPC_if)) {
344 auto Cond = cast<OMPIfClause>(C)->getCondition();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000345 EmitOMPIfClause(CGF, Cond, [&](bool ThenBlock) {
Alexey Bataevd74d0602014-10-13 06:02:40 +0000346 if (ThenBlock)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000347 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000348 else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000349 CGF.CGM.getOpenMPRuntime().emitSerialCall(CGF, S.getLocStart(),
350 OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000351 });
Alexey Bataevb2059782014-10-13 08:23:51 +0000352 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000353 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
354}
355
356void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
357 LexicalScope Scope(*this, S.getSourceRange());
358 // Emit parallel region as a standalone region.
359 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
360 OMPPrivateScope PrivateScope(CGF);
361 CGF.EmitOMPPrivateClause(S, PrivateScope);
362 CGF.EmitOMPFirstprivateClause(S, PrivateScope);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000363 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000364 if (PrivateScope.Privatize())
365 // Emit implicit barrier to synchronize threads and avoid data races.
366 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
367 OMPD_unknown);
368 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000369 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000370 // Emit implicit barrier at the end of the 'parallel' directive.
371 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
372 OMPD_unknown);
373 };
374 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000375}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000376
Alexander Musmand196ef22014-10-07 08:57:09 +0000377void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000378 bool SeparateIter) {
379 RunCleanupsScope BodyScope(*this);
380 // Update counters values on current iteration.
381 for (auto I : S.updates()) {
382 EmitIgnoredExpr(I);
383 }
Alexander Musman3276a272015-03-21 10:12:56 +0000384 // Update the linear variables.
385 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
386 for (auto U : C->updates()) {
387 EmitIgnoredExpr(U);
388 }
389 }
390
Alexander Musmana5f070a2014-10-01 06:03:56 +0000391 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000392 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000393 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
394 // Emit loop body.
395 EmitStmt(S.getBody());
396 // The end (updates/cleanups).
397 EmitBlock(Continue.getBlock());
398 BreakContinueStack.pop_back();
399 if (SeparateIter) {
400 // TODO: Update lastprivates if the SeparateIter flag is true.
401 // This will be implemented in a follow-up OMPLastprivateClause patch, but
402 // result should be still correct without it, as we do not make these
403 // variables private yet.
404 }
405}
406
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407void CodeGenFunction::EmitOMPInnerLoop(
408 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
409 const Expr *IncExpr,
410 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000411 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000412 auto Cnt = getPGORegionCounter(&S);
413
414 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000415 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000416 EmitBlock(CondBlock);
417 LoopStack.push(CondBlock);
418
419 // If there are any cleanups between here and the loop-exit scope,
420 // create a block to stage a loop exit along.
421 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000422 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000423 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000424
Alexander Musmand196ef22014-10-07 08:57:09 +0000425 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000426
Alexey Bataev2df54a02015-03-12 08:53:29 +0000427 // Emit condition.
428 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, Cnt.getCount());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000429 if (ExitBlock != LoopExit.getBlock()) {
430 EmitBlock(ExitBlock);
431 EmitBranchThroughCleanup(LoopExit);
432 }
433
434 EmitBlock(LoopBody);
435 Cnt.beginRegion(Builder);
436
437 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000438 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000439 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
440
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000441 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000442
443 // Emit "IV = IV + 1" and a back-edge to the condition block.
444 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000445 EmitIgnoredExpr(IncExpr);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000446 BreakContinueStack.pop_back();
447 EmitBranch(CondBlock);
448 LoopStack.pop();
449 // Emit the fall-through block.
450 EmitBlock(LoopExit.getBlock());
451}
452
453void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
454 auto IC = S.counters().begin();
455 for (auto F : S.finals()) {
456 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
457 EmitIgnoredExpr(F);
458 }
459 ++IC;
460 }
Alexander Musman3276a272015-03-21 10:12:56 +0000461 // Emit the final values of the linear variables.
462 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
463 for (auto F : C->finals()) {
464 EmitIgnoredExpr(F);
465 }
466 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000467}
468
Alexander Musman09184fe2014-09-30 05:29:28 +0000469static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
470 const OMPAlignedClause &Clause) {
471 unsigned ClauseAlignment = 0;
472 if (auto AlignmentExpr = Clause.getAlignment()) {
473 auto AlignmentCI =
474 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
475 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
476 }
477 for (auto E : Clause.varlists()) {
478 unsigned Alignment = ClauseAlignment;
479 if (Alignment == 0) {
480 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000481 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000482 // alignments for SIMD instructions on the target platforms are assumed.
483 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
484 E->getType());
485 }
486 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
487 "alignment is not power of 2");
488 if (Alignment != 0) {
489 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
490 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
491 }
492 }
493}
494
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000495static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
496 CodeGenFunction::OMPPrivateScope &LoopScope,
497 ArrayRef<Expr *> Counters) {
498 for (auto *E : Counters) {
499 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
500 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
501 // Emit var without initialization.
502 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
503 CGF.EmitAutoVarCleanups(VarEmission);
504 return VarEmission.getAllocatedAddress();
505 });
506 assert(IsRegistered && "counter already registered as private");
507 // Silence the warning about unused variable.
508 (void)IsRegistered;
509 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000510}
511
Alexander Musman3276a272015-03-21 10:12:56 +0000512static void
513EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
514 CodeGenFunction::OMPPrivateScope &PrivateScope) {
515 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
516 for (auto *E : Clause->varlists()) {
517 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
518 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
519 // Emit var without initialization.
520 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
521 CGF.EmitAutoVarCleanups(VarEmission);
522 return VarEmission.getAllocatedAddress();
523 });
524 assert(IsRegistered && "linear var already registered as private");
525 // Silence the warning about unused variable.
526 (void)IsRegistered;
527 }
528 }
529}
530
Alexander Musman515ad8c2014-05-22 08:54:05 +0000531void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000532 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
533 // Pragma 'simd' code depends on presence of 'lastprivate'.
534 // If present, we have to separate last iteration of the loop:
535 //
536 // if (LastIteration != 0) {
537 // for (IV in 0..LastIteration-1) BODY;
538 // BODY with updates of lastprivate vars;
539 // <Final counter/linear vars updates>;
540 // }
541 //
542 // otherwise (when there's no lastprivate):
543 //
544 // for (IV in 0..LastIteration) BODY;
545 // <Final counter/linear vars updates>;
546 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000547
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000548 // Walk clauses and process safelen/lastprivate.
549 bool SeparateIter = false;
550 CGF.LoopStack.setParallel();
551 CGF.LoopStack.setVectorizerEnable(true);
552 for (auto C : S.clauses()) {
553 switch (C->getClauseKind()) {
554 case OMPC_safelen: {
555 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
556 AggValueSlot::ignored(), true);
557 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
558 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
559 // In presence of finite 'safelen', it may be unsafe to mark all
560 // the memory instructions parallel, because loop-carried
561 // dependences of 'safelen' iterations are possible.
562 CGF.LoopStack.setParallel(false);
563 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000564 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000565 case OMPC_aligned:
566 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
567 break;
568 case OMPC_lastprivate:
569 SeparateIter = true;
570 break;
571 default:
572 // Not handled yet
573 ;
574 }
575 }
Alexander Musman3276a272015-03-21 10:12:56 +0000576
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000577 // Emit inits for the linear variables.
578 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
579 for (auto Init : C->inits()) {
580 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
581 CGF.EmitVarDecl(*D);
582 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000583 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000584
585 // Emit the loop iteration variable.
586 const Expr *IVExpr = S.getIterationVariable();
587 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
588 CGF.EmitVarDecl(*IVDecl);
589 CGF.EmitIgnoredExpr(S.getInit());
590
591 // Emit the iterations count variable.
592 // If it is not a variable, Sema decided to calculate iterations count on
593 // each
594 // iteration (e.g., it is foldable into a constant).
595 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
596 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
597 // Emit calculation of the iterations count.
598 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000599 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000600
601 // Emit the linear steps for the linear clauses.
602 // If a step is not constant, it is pre-calculated before the loop.
603 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
604 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
605 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
606 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
607 // Emit calculation of the linear step.
608 CGF.EmitIgnoredExpr(CS);
609 }
610 }
611
612 if (SeparateIter) {
613 // Emit: if (LastIteration > 0) - begin.
614 RegionCounter Cnt = CGF.getPGORegionCounter(&S);
615 auto ThenBlock = CGF.createBasicBlock("simd.if.then");
616 auto ContBlock = CGF.createBasicBlock("simd.if.end");
617 CGF.EmitBranchOnBoolExpr(S.getPreCond(), ThenBlock, ContBlock,
618 Cnt.getCount());
619 CGF.EmitBlock(ThenBlock);
620 Cnt.beginRegion(CGF.Builder);
621 // Emit 'then' code.
622 {
623 OMPPrivateScope LoopScope(CGF);
624 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
625 EmitPrivateLinearVars(CGF, S, LoopScope);
626 CGF.EmitOMPPrivateClause(S, LoopScope);
627 (void)LoopScope.Privatize();
628 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
629 S.getCond(/*SeparateIter=*/true), S.getInc(),
630 [&S](CodeGenFunction &CGF) {
631 CGF.EmitOMPLoopBody(S);
632 CGF.EmitStopPoint(&S);
633 });
634 CGF.EmitOMPLoopBody(S, /* SeparateIter */ true);
635 }
636 CGF.EmitOMPSimdFinal(S);
637 // Emit: if (LastIteration != 0) - end.
638 CGF.EmitBranch(ContBlock);
639 CGF.EmitBlock(ContBlock, true);
640 } else {
641 {
642 OMPPrivateScope LoopScope(CGF);
643 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
644 EmitPrivateLinearVars(CGF, S, LoopScope);
645 CGF.EmitOMPPrivateClause(S, LoopScope);
646 (void)LoopScope.Privatize();
647 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
648 S.getCond(/*SeparateIter=*/false), S.getInc(),
649 [&S](CodeGenFunction &CGF) {
650 CGF.EmitOMPLoopBody(S);
651 CGF.EmitStopPoint(&S);
652 });
653 }
654 CGF.EmitOMPSimdFinal(S);
655 }
656 };
657 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000658}
659
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000660void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
661 const OMPLoopDirective &S,
662 OMPPrivateScope &LoopScope,
663 llvm::Value *LB, llvm::Value *UB,
664 llvm::Value *ST, llvm::Value *IL,
665 llvm::Value *Chunk) {
666 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000667
668 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
669 const bool Dynamic = RT.isDynamic(ScheduleKind);
670
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000671 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
672 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000673
674 // Emit outer loop.
675 //
676 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000677 // When schedule(dynamic,chunk_size) is specified, the iterations are
678 // distributed to threads in the team in chunks as the threads request them.
679 // Each thread executes a chunk of iterations, then requests another chunk,
680 // until no chunks remain to be distributed. Each chunk contains chunk_size
681 // iterations, except for the last chunk to be distributed, which may have
682 // fewer iterations. When no chunk_size is specified, it defaults to 1.
683 //
684 // When schedule(guided,chunk_size) is specified, the iterations are assigned
685 // to threads in the team in chunks as the executing threads request them.
686 // Each thread executes a chunk of iterations, then requests another chunk,
687 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
688 // each chunk is proportional to the number of unassigned iterations divided
689 // by the number of threads in the team, decreasing to 1. For a chunk_size
690 // with value k (greater than 1), the size of each chunk is determined in the
691 // same way, with the restriction that the chunks do not contain fewer than k
692 // iterations (except for the last chunk to be assigned, which may have fewer
693 // than k iterations).
694 //
695 // When schedule(auto) is specified, the decision regarding scheduling is
696 // delegated to the compiler and/or runtime system. The programmer gives the
697 // implementation the freedom to choose any possible mapping of iterations to
698 // threads in the team.
699 //
700 // When schedule(runtime) is specified, the decision regarding scheduling is
701 // deferred until run time, and the schedule and chunk size are taken from the
702 // run-sched-var ICV. If the ICV is set to auto, the schedule is
703 // implementation defined
704 //
705 // while(__kmpc_dispatch_next(&LB, &UB)) {
706 // idx = LB;
707 // while (idx <= UB) { BODY; ++idx; } // inner loop
708 // }
709 //
710 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000711 // When schedule(static, chunk_size) is specified, iterations are divided into
712 // chunks of size chunk_size, and the chunks are assigned to the threads in
713 // the team in a round-robin fashion in the order of the thread number.
714 //
715 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
716 // while (idx <= UB) { BODY; ++idx; } // inner loop
717 // LB = LB + ST;
718 // UB = UB + ST;
719 // }
720 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000721
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000722 const Expr *IVExpr = S.getIterationVariable();
723 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
724 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
725
Alexander Musman92bdaab2015-03-12 13:37:50 +0000726 RT.emitForInit(
727 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
728 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
729 Chunk);
730
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000731 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
732
733 // Start the loop with a block that tests the condition.
734 auto CondBlock = createBasicBlock("omp.dispatch.cond");
735 EmitBlock(CondBlock);
736 LoopStack.push(CondBlock);
737
738 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000739 if (!Dynamic) {
740 // UB = min(UB, GlobalUB)
741 EmitIgnoredExpr(S.getEnsureUpperBound());
742 // IV = LB
743 EmitIgnoredExpr(S.getInit());
744 // IV < UB
745 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
746 } else {
747 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
748 IL, LB, UB, ST);
749 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000750
751 // If there are any cleanups between here and the loop-exit scope,
752 // create a block to stage a loop exit along.
753 auto ExitBlock = LoopExit.getBlock();
754 if (LoopScope.requiresCleanups())
755 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
756
757 auto LoopBody = createBasicBlock("omp.dispatch.body");
758 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
759 if (ExitBlock != LoopExit.getBlock()) {
760 EmitBlock(ExitBlock);
761 EmitBranchThroughCleanup(LoopExit);
762 }
763 EmitBlock(LoopBody);
764
Alexander Musman92bdaab2015-03-12 13:37:50 +0000765 // Emit "IV = LB" (in case of static schedule, we have already calculated new
766 // LB for loop condition and emitted it above).
767 if (Dynamic)
768 EmitIgnoredExpr(S.getInit());
769
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000770 // Create a block for the increment.
771 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
772 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
773
Alexey Bataev2df54a02015-03-12 08:53:29 +0000774 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000775 S.getCond(/*SeparateIter=*/false), S.getInc(),
776 [&S](CodeGenFunction &CGF) {
777 CGF.EmitOMPLoopBody(S);
778 CGF.EmitStopPoint(&S);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000779 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000780
781 EmitBlock(Continue.getBlock());
782 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000783 if (!Dynamic) {
784 // Emit "LB = LB + Stride", "UB = UB + Stride".
785 EmitIgnoredExpr(S.getNextLowerBound());
786 EmitIgnoredExpr(S.getNextUpperBound());
787 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000788
789 EmitBranch(CondBlock);
790 LoopStack.pop();
791 // Emit the fall-through block.
792 EmitBlock(LoopExit.getBlock());
793
794 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000795 // FIXME: Also call fini for ordered loops with dynamic scheduling.
796 if (!Dynamic)
797 RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000798}
799
Alexander Musmanc6388682014-12-15 07:07:06 +0000800/// \brief Emit a helper variable and return corresponding lvalue.
801static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
802 const DeclRefExpr *Helper) {
803 auto VDecl = cast<VarDecl>(Helper->getDecl());
804 CGF.EmitVarDecl(*VDecl);
805 return CGF.EmitLValue(Helper);
806}
807
808void CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
809 // Emit the loop iteration variable.
810 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
811 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
812 EmitVarDecl(*IVDecl);
813
814 // Emit the iterations count variable.
815 // If it is not a variable, Sema decided to calculate iterations count on each
816 // iteration (e.g., it is foldable into a constant).
817 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
818 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
819 // Emit calculation of the iterations count.
820 EmitIgnoredExpr(S.getCalcLastIteration());
821 }
822
823 auto &RT = CGM.getOpenMPRuntime();
824
825 // Check pre-condition.
826 {
827 // Skip the entire loop if we don't meet the precondition.
828 RegionCounter Cnt = getPGORegionCounter(&S);
829 auto ThenBlock = createBasicBlock("omp.precond.then");
830 auto ContBlock = createBasicBlock("omp.precond.end");
831 EmitBranchOnBoolExpr(S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
832 EmitBlock(ThenBlock);
833 Cnt.beginRegion(Builder);
834 // Emit 'then' code.
835 {
836 // Emit helper vars inits.
837 LValue LB =
838 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
839 LValue UB =
840 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
841 LValue ST =
842 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
843 LValue IL =
844 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
845
846 OMPPrivateScope LoopScope(*this);
847 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +0000848 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +0000849
850 // Detect the loop schedule kind and chunk.
851 auto ScheduleKind = OMPC_SCHEDULE_unknown;
852 llvm::Value *Chunk = nullptr;
853 if (auto C = cast_or_null<OMPScheduleClause>(
854 S.getSingleClause(OMPC_schedule))) {
855 ScheduleKind = C->getScheduleKind();
856 if (auto Ch = C->getChunkSize()) {
857 Chunk = EmitScalarExpr(Ch);
858 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
859 S.getIterationVariable()->getType());
860 }
861 }
862 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
863 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
864 if (RT.isStaticNonchunked(ScheduleKind,
865 /* Chunked */ Chunk != nullptr)) {
866 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
867 // When no chunk_size is specified, the iteration space is divided into
868 // chunks that are approximately equal in size, and at most one chunk is
869 // distributed to each thread. Note that the size of the chunks is
870 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000871 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
872 IL.getAddress(), LB.getAddress(), UB.getAddress(),
873 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +0000874 // UB = min(UB, GlobalUB);
875 EmitIgnoredExpr(S.getEnsureUpperBound());
876 // IV = LB;
877 EmitIgnoredExpr(S.getInit());
878 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +0000879 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
880 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000881 [&S](CodeGenFunction &CGF) {
882 CGF.EmitOMPLoopBody(S);
883 CGF.EmitStopPoint(&S);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000884 });
Alexander Musmanc6388682014-12-15 07:07:06 +0000885 // Tell the runtime we are done.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000886 RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000887 } else {
888 // Emit the outer loop, which requests its work chunk [LB..UB] from
889 // runtime and runs the inner loop to process it.
890 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
891 UB.getAddress(), ST.getAddress(), IL.getAddress(),
892 Chunk);
893 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000894 }
895 // We're now done with the loop, so jump to the continuation block.
896 EmitBranch(ContBlock);
897 EmitBlock(ContBlock, true);
898 }
899}
900
901void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000902 LexicalScope Scope(*this, S.getSourceRange());
903 auto &&CodeGen =
904 [&S](CodeGenFunction &CGF) { CGF.EmitOMPWorksharingLoop(S); };
905 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +0000906
907 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +0000908 if (!S.getSingleClause(OMPC_nowait)) {
909 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
910 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000911}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +0000912
Alexander Musmanf82886e2014-09-18 05:12:34 +0000913void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
914 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
915}
916
Alexey Bataev2df54a02015-03-12 08:53:29 +0000917static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
918 const Twine &Name,
919 llvm::Value *Init = nullptr) {
920 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
921 if (Init)
922 CGF.EmitScalarInit(Init, LVal);
923 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +0000924}
925
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000926static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
927 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +0000928 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
929 auto *CS = dyn_cast<CompoundStmt>(Stmt);
930 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000931 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
932 auto &C = CGF.CGM.getContext();
933 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
934 // Emit helper vars inits.
935 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
936 CGF.Builder.getInt32(0));
937 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
938 LValue UB =
939 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
940 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
941 CGF.Builder.getInt32(1));
942 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
943 CGF.Builder.getInt32(0));
944 // Loop counter.
945 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
946 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000947 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000948 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000949 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000950 // Generate condition for loop.
951 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
952 OK_Ordinary, S.getLocStart(),
953 /*fpContractable=*/false);
954 // Increment for loop counter.
955 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
956 OK_Ordinary, S.getLocStart());
957 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
958 // Iterate through all sections and emit a switch construct:
959 // switch (IV) {
960 // case 0:
961 // <SectionStmt[0]>;
962 // break;
963 // ...
964 // case <NumSection> - 1:
965 // <SectionStmt[<NumSection> - 1]>;
966 // break;
967 // }
968 // .omp.sections.exit:
969 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
970 auto *SwitchStmt = CGF.Builder.CreateSwitch(
971 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
972 CS->size());
973 unsigned CaseNumber = 0;
974 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
975 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
976 CGF.EmitBlock(CaseBB);
977 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
978 CGF.EmitStmt(*C);
979 CGF.EmitBranch(ExitBB);
980 }
981 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
982 };
983 // Emit static non-chunked loop.
984 CGF.CGM.getOpenMPRuntime().emitForInit(
985 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
986 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
987 ST.getAddress());
988 // UB = min(UB, GlobalUB);
989 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
990 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
991 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
992 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
993 // IV = LB;
994 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
995 // while (idx <= UB) { BODY; ++idx; }
996 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen);
997 // Tell the runtime we are done.
998 CGF.CGM.getOpenMPRuntime().emitForFinish(CGF, S.getLocStart(),
999 OMPC_SCHEDULE_static);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001000 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001001
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001002 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1003 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001004 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001005 // If only one section is found - no need to generate loop, emit as a single
1006 // region.
1007 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
1008 CGF.EmitStmt(Stmt);
1009 CGF.EnsureInsertPoint();
1010 };
1011 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1012 llvm::None, llvm::None,
1013 llvm::None, llvm::None);
1014 return OMPD_single;
1015}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001016
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001017void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1018 LexicalScope Scope(*this, S.getSourceRange());
1019 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001020 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001021 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001022 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001023 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001024}
1025
1026void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001027 LexicalScope Scope(*this, S.getSourceRange());
1028 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1029 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1030 CGF.EnsureInsertPoint();
1031 };
1032 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001033}
1034
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001035void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001036 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001037 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001038 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001039 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001040 // Check if there are any 'copyprivate' clauses associated with this
1041 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001042 // construct.
1043 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1044 return C->getClauseKind() == OMPC_copyprivate;
1045 };
1046 // Build a list of copyprivate variables along with helper expressions
1047 // (<source>, <destination>, <destination>=<source> expressions)
1048 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1049 CopyprivateFilter)> CopyprivateIter;
1050 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1051 auto *C = cast<OMPCopyprivateClause>(*I);
1052 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001053 DestExprs.append(C->destination_exprs().begin(),
1054 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001055 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001056 AssignmentOps.append(C->assignment_ops().begin(),
1057 C->assignment_ops().end());
1058 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001059 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001060 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001061 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1062 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1063 CGF.EnsureInsertPoint();
1064 };
1065 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001066 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001067 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001068 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001069 if (!S.getSingleClause(OMPC_nowait)) {
1070 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1071 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001072}
1073
Alexey Bataev8d690652014-12-04 07:23:53 +00001074void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001075 LexicalScope Scope(*this, S.getSourceRange());
1076 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1077 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1078 CGF.EnsureInsertPoint();
1079 };
1080 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001081}
1082
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001083void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001084 LexicalScope Scope(*this, S.getSourceRange());
1085 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1086 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1087 CGF.EnsureInsertPoint();
1088 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001089 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001090 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001091}
1092
Alexey Bataev671605e2015-04-13 05:28:11 +00001093void CodeGenFunction::EmitOMPParallelForDirective(
1094 const OMPParallelForDirective &S) {
1095 // Emit directive as a combined directive that consists of two implicit
1096 // directives: 'parallel' with 'for' directive.
1097 LexicalScope Scope(*this, S.getSourceRange());
1098 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1099 CGF.EmitOMPWorksharingLoop(S);
1100 // Emit implicit barrier at the end of parallel region, but this barrier
1101 // is at the end of 'for' directive, so emit it as the implicit barrier for
1102 // this 'for' directive.
1103 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1104 OMPD_parallel);
1105 };
1106 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001107}
1108
Alexander Musmane4e893b2014-09-23 09:33:00 +00001109void CodeGenFunction::EmitOMPParallelForSimdDirective(
1110 const OMPParallelForSimdDirective &) {
1111 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1112}
1113
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001114void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001115 const OMPParallelSectionsDirective &S) {
1116 // Emit directive as a combined directive that consists of two implicit
1117 // directives: 'parallel' with 'sections' directive.
1118 LexicalScope Scope(*this, S.getSourceRange());
1119 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1120 (void)emitSections(CGF, S);
1121 // Emit implicit barrier at the end of parallel region.
1122 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1123 OMPD_parallel);
1124 };
1125 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001126}
1127
Alexey Bataev62b63b12015-03-10 07:28:44 +00001128void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1129 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001131 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1132 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1133 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001135 // The first function argument for tasks is a thread id, the second one is a
1136 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001137 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1138 if (*PartId) {
1139 // TODO: emit code for untied tasks.
1140 }
1141 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1142 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001143 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001144 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001145 // Check if we should emit tied or untied task.
1146 bool Tied = !S.getSingleClause(OMPC_untied);
1147 // Check if the task is final
1148 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1149 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1150 // If the condition constant folds and can be elided, try to avoid emitting
1151 // the condition and the dead arm of the if/else.
1152 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1153 bool CondConstant;
1154 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1155 Final.setInt(CondConstant);
1156 else
1157 Final.setPointer(EvaluateExprAsBool(Cond));
1158 } else {
1159 // By default the task is not final.
1160 Final.setInt(/*IntVal=*/false);
1161 }
1162 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
1163 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
1164 OutlinedFn, SharedsTy, CapturedStruct);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001165}
1166
Alexey Bataev9f797f32015-02-05 05:57:51 +00001167void CodeGenFunction::EmitOMPTaskyieldDirective(
1168 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001169 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001170}
1171
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001172void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001173 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001174}
1175
Alexey Bataev2df347a2014-07-18 10:17:07 +00001176void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1177 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1178}
1179
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001180void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001181 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1182 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1183 auto FlushClause = cast<OMPFlushClause>(C);
1184 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1185 FlushClause->varlist_end());
1186 }
1187 return llvm::None;
1188 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001189}
1190
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001191void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &) {
1192 llvm_unreachable("CodeGen for 'omp ordered' is not supported yet.");
1193}
1194
Alexey Bataevb57056f2015-01-22 06:17:56 +00001195static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1196 QualType SrcType, QualType DestType) {
1197 assert(CGF.hasScalarEvaluationKind(DestType) &&
1198 "DestType must have scalar evaluation kind.");
1199 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1200 return Val.isScalar()
1201 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1202 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1203 DestType);
1204}
1205
1206static CodeGenFunction::ComplexPairTy
1207convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1208 QualType DestType) {
1209 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1210 "DestType must have complex evaluation kind.");
1211 CodeGenFunction::ComplexPairTy ComplexVal;
1212 if (Val.isScalar()) {
1213 // Convert the input element to the element type of the complex.
1214 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1215 auto ScalarVal =
1216 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1217 ComplexVal = CodeGenFunction::ComplexPairTy(
1218 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1219 } else {
1220 assert(Val.isComplex() && "Must be a scalar or complex.");
1221 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1222 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1223 ComplexVal.first = CGF.EmitScalarConversion(
1224 Val.getComplexVal().first, SrcElementType, DestElementType);
1225 ComplexVal.second = CGF.EmitScalarConversion(
1226 Val.getComplexVal().second, SrcElementType, DestElementType);
1227 }
1228 return ComplexVal;
1229}
1230
1231static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1232 const Expr *X, const Expr *V,
1233 SourceLocation Loc) {
1234 // v = x;
1235 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1236 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1237 LValue XLValue = CGF.EmitLValue(X);
1238 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001239 RValue Res = XLValue.isGlobalReg()
1240 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1241 : CGF.EmitAtomicLoad(XLValue, Loc,
1242 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001243 : llvm::Monotonic,
1244 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001245 // OpenMP, 2.12.6, atomic Construct
1246 // Any atomic construct with a seq_cst clause forces the atomically
1247 // performed operation to include an implicit flush operation without a
1248 // list.
1249 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001250 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001251 switch (CGF.getEvaluationKind(V->getType())) {
1252 case TEK_Scalar:
1253 CGF.EmitStoreOfScalar(
1254 convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
1255 break;
1256 case TEK_Complex:
1257 CGF.EmitStoreOfComplex(
1258 convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
1259 /*isInit=*/false);
1260 break;
1261 case TEK_Aggregate:
1262 llvm_unreachable("Must be a scalar or complex.");
1263 }
1264}
1265
Alexey Bataevb8329262015-02-27 06:33:30 +00001266static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1267 const Expr *X, const Expr *E,
1268 SourceLocation Loc) {
1269 // x = expr;
1270 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
1271 LValue XLValue = CGF.EmitLValue(X);
1272 RValue ExprRValue = CGF.EmitAnyExpr(E);
1273 if (XLValue.isGlobalReg())
1274 CGF.EmitStoreThroughGlobalRegLValue(ExprRValue, XLValue);
1275 else
1276 CGF.EmitAtomicStore(ExprRValue, XLValue,
1277 IsSeqCst ? llvm::SequentiallyConsistent
1278 : llvm::Monotonic,
1279 XLValue.isVolatile(), /*IsInit=*/false);
1280 // OpenMP, 2.12.6, atomic Construct
1281 // Any atomic construct with a seq_cst clause forces the atomically
1282 // performed operation to include an implicit flush operation without a
1283 // list.
1284 if (IsSeqCst)
1285 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1286}
1287
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001288bool emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update,
1289 BinaryOperatorKind BO, llvm::AtomicOrdering AO,
1290 bool IsXLHSInRHSPart) {
1291 auto &Context = CGF.CGM.getContext();
1292 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001293 // expression is simple and atomic is allowed for the given type for the
1294 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001295 if (BO == BO_Comma || !Update.isScalar() ||
1296 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1297 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1298 (Update.getScalarVal()->getType() !=
1299 X.getAddress()->getType()->getPointerElementType())) ||
1300 !Context.getTargetInfo().hasBuiltinAtomic(
1301 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
1302 return false;
1303
1304 llvm::AtomicRMWInst::BinOp RMWOp;
1305 switch (BO) {
1306 case BO_Add:
1307 RMWOp = llvm::AtomicRMWInst::Add;
1308 break;
1309 case BO_Sub:
1310 if (!IsXLHSInRHSPart)
1311 return false;
1312 RMWOp = llvm::AtomicRMWInst::Sub;
1313 break;
1314 case BO_And:
1315 RMWOp = llvm::AtomicRMWInst::And;
1316 break;
1317 case BO_Or:
1318 RMWOp = llvm::AtomicRMWInst::Or;
1319 break;
1320 case BO_Xor:
1321 RMWOp = llvm::AtomicRMWInst::Xor;
1322 break;
1323 case BO_LT:
1324 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1325 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1326 : llvm::AtomicRMWInst::Max)
1327 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1328 : llvm::AtomicRMWInst::UMax);
1329 break;
1330 case BO_GT:
1331 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1332 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1333 : llvm::AtomicRMWInst::Min)
1334 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1335 : llvm::AtomicRMWInst::UMin);
1336 break;
1337 case BO_Mul:
1338 case BO_Div:
1339 case BO_Rem:
1340 case BO_Shl:
1341 case BO_Shr:
1342 case BO_LAnd:
1343 case BO_LOr:
1344 return false;
1345 case BO_PtrMemD:
1346 case BO_PtrMemI:
1347 case BO_LE:
1348 case BO_GE:
1349 case BO_EQ:
1350 case BO_NE:
1351 case BO_Assign:
1352 case BO_AddAssign:
1353 case BO_SubAssign:
1354 case BO_AndAssign:
1355 case BO_OrAssign:
1356 case BO_XorAssign:
1357 case BO_MulAssign:
1358 case BO_DivAssign:
1359 case BO_RemAssign:
1360 case BO_ShlAssign:
1361 case BO_ShrAssign:
1362 case BO_Comma:
1363 llvm_unreachable("Unsupported atomic update operation");
1364 }
1365 auto *UpdateVal = Update.getScalarVal();
1366 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1367 UpdateVal = CGF.Builder.CreateIntCast(
1368 IC, X.getAddress()->getType()->getPointerElementType(),
1369 X.getType()->hasSignedIntegerRepresentation());
1370 }
1371 CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1372 return true;
1373}
1374
1375void CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
1376 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1377 llvm::AtomicOrdering AO, SourceLocation Loc,
1378 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1379 // Update expressions are allowed to have the following forms:
1380 // x binop= expr; -> xrval + expr;
1381 // x++, ++x -> xrval + 1;
1382 // x--, --x -> xrval - 1;
1383 // x = x binop expr; -> xrval binop expr
1384 // x = expr Op x; - > expr binop xrval;
1385 if (!emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart)) {
1386 if (X.isGlobalReg()) {
1387 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1388 // 'xrval'.
1389 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1390 } else {
1391 // Perform compare-and-swap procedure.
1392 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001393 }
1394 }
Alexey Bataevb4505a72015-03-30 05:20:59 +00001395}
1396
1397static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1398 const Expr *X, const Expr *E,
1399 const Expr *UE, bool IsXLHSInRHSPart,
1400 SourceLocation Loc) {
1401 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1402 "Update expr in 'atomic update' must be a binary operator.");
1403 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1404 // Update expressions are allowed to have the following forms:
1405 // x binop= expr; -> xrval + expr;
1406 // x++, ++x -> xrval + 1;
1407 // x--, --x -> xrval - 1;
1408 // x = x binop expr; -> xrval binop expr
1409 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001410 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001411 LValue XLValue = CGF.EmitLValue(X);
1412 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001413 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001414 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1415 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1416 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1417 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1418 auto Gen =
1419 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1420 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1421 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1422 return CGF.EmitAnyExpr(UE);
1423 };
1424 CGF.EmitOMPAtomicSimpleUpdateExpr(XLValue, ExprRValue, BOUE->getOpcode(),
1425 IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001426 // OpenMP, 2.12.6, atomic Construct
1427 // Any atomic construct with a seq_cst clause forces the atomically
1428 // performed operation to include an implicit flush operation without a
1429 // list.
1430 if (IsSeqCst)
1431 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1432}
1433
Alexey Bataevb57056f2015-01-22 06:17:56 +00001434static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
1435 bool IsSeqCst, const Expr *X, const Expr *V,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001436 const Expr *E, const Expr *UE,
1437 bool IsXLHSInRHSPart, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001438 switch (Kind) {
1439 case OMPC_read:
1440 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1441 break;
1442 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001443 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1444 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001445 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001446 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001447 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1448 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001449 case OMPC_capture:
1450 llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
1451 case OMPC_if:
1452 case OMPC_final:
1453 case OMPC_num_threads:
1454 case OMPC_private:
1455 case OMPC_firstprivate:
1456 case OMPC_lastprivate:
1457 case OMPC_reduction:
1458 case OMPC_safelen:
1459 case OMPC_collapse:
1460 case OMPC_default:
1461 case OMPC_seq_cst:
1462 case OMPC_shared:
1463 case OMPC_linear:
1464 case OMPC_aligned:
1465 case OMPC_copyin:
1466 case OMPC_copyprivate:
1467 case OMPC_flush:
1468 case OMPC_proc_bind:
1469 case OMPC_schedule:
1470 case OMPC_ordered:
1471 case OMPC_nowait:
1472 case OMPC_untied:
1473 case OMPC_threadprivate:
1474 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001475 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1476 }
1477}
1478
1479void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1480 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1481 OpenMPClauseKind Kind = OMPC_unknown;
1482 for (auto *C : S.clauses()) {
1483 // Find first clause (skip seq_cst clause, if it is first).
1484 if (C->getClauseKind() != OMPC_seq_cst) {
1485 Kind = C->getClauseKind();
1486 break;
1487 }
1488 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001489
1490 const auto *CS =
1491 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
1492 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
1493 enterFullExpression(EWC);
Alexey Bataev10fec572015-03-11 04:48:56 +00001494
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001495 LexicalScope Scope(*this, S.getSourceRange());
1496 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
1497 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
1498 S.getUpdateExpr(), S.isXLHSInRHSPart(), S.getLocStart());
1499 };
1500 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001501}
1502
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001503void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1504 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1505}
1506
Alexey Bataev13314bf2014-10-09 04:18:56 +00001507void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1508 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1509}
1510