blob: c83dda255d673f6bb49ece64ccf551237f521093 [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
Alexey Bataev69c62a92015-04-15 04:52:20 +0000161bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
162 OMPPrivateScope &PrivateScope) {
163 auto FirstprivateFilter = [](const OMPClause *C) -> bool {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000164 return C->getClauseKind() == OMPC_firstprivate;
165 };
Alexey Bataev69c62a92015-04-15 04:52:20 +0000166 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
167 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
168 FirstprivateFilter)> I(D.clauses(), FirstprivateFilter);
169 I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000170 auto *C = cast<OMPFirstprivateClause>(*I);
171 auto IRef = C->varlist_begin();
172 auto InitsRef = C->inits().begin();
173 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000174 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000175 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
176 EmittedAsFirstprivate.insert(OrigVD);
177 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
178 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
179 bool IsRegistered;
180 DeclRefExpr DRE(
181 const_cast<VarDecl *>(OrigVD),
182 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
183 OrigVD) != nullptr,
184 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
185 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
186 if (OrigVD->getType()->isArrayType()) {
187 // Emit VarDecl with copy init for arrays.
188 // Get the address of the original variable captured in current
189 // captured region.
190 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
191 auto Emission = EmitAutoVarAlloca(*VD);
192 auto *Init = VD->getInit();
193 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
194 // Perform simple memcpy.
195 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
196 (*IRef)->getType());
197 } else {
198 EmitOMPAggregateAssign(
199 Emission.getAllocatedAddress(), OriginalAddr,
200 (*IRef)->getType(),
201 [this, VDInit, Init](llvm::Value *DestElement,
202 llvm::Value *SrcElement) {
203 // Clean up any temporaries needed by the initialization.
204 RunCleanupsScope InitScope(*this);
205 // Emit initialization for single element.
206 LocalDeclMap[VDInit] = SrcElement;
207 EmitAnyExprToMem(Init, DestElement,
208 Init->getType().getQualifiers(),
209 /*IsInitializer*/ false);
210 LocalDeclMap.erase(VDInit);
211 });
212 }
213 EmitAutoVarCleanups(Emission);
214 return Emission.getAllocatedAddress();
215 });
216 } else {
217 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
218 // Emit private VarDecl with copy init.
219 // Remap temp VDInit variable to the address of the original
220 // variable
221 // (for proper handling of captured global variables).
222 LocalDeclMap[VDInit] = OriginalAddr;
223 EmitDecl(*VD);
224 LocalDeclMap.erase(VDInit);
225 return GetAddrOfLocalVar(VD);
226 });
227 }
228 assert(IsRegistered &&
229 "firstprivate var already registered as private");
230 // Silence the warning about unused variable.
231 (void)IsRegistered;
232 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000233 ++IRef, ++InitsRef;
234 }
235 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000236 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000237}
238
Alexey Bataev03b340a2014-10-21 03:16:40 +0000239void CodeGenFunction::EmitOMPPrivateClause(
240 const OMPExecutableDirective &D,
241 CodeGenFunction::OMPPrivateScope &PrivateScope) {
242 auto PrivateFilter = [](const OMPClause *C) -> bool {
243 return C->getClauseKind() == OMPC_private;
244 };
245 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
246 I(D.clauses(), PrivateFilter); I; ++I) {
247 auto *C = cast<OMPPrivateClause>(*I);
248 auto IRef = C->varlist_begin();
249 for (auto IInit : C->private_copies()) {
250 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
251 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
252 bool IsRegistered =
253 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value * {
254 // Emit private VarDecl with copy init.
255 EmitDecl(*VD);
256 return GetAddrOfLocalVar(VD);
257 });
Alexander Musman7931b982015-03-16 07:14:41 +0000258 assert(IsRegistered && "private var already registered as private");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000259 // Silence the warning about unused variable.
260 (void)IsRegistered;
261 ++IRef;
262 }
263 }
264}
265
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000266bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
267 // threadprivate_var1 = master_threadprivate_var1;
268 // operator=(threadprivate_var2, master_threadprivate_var2);
269 // ...
270 // __kmpc_barrier(&loc, global_tid);
271 auto CopyinFilter = [](const OMPClause *C) -> bool {
272 return C->getClauseKind() == OMPC_copyin;
273 };
274 llvm::DenseSet<const VarDecl *> CopiedVars;
275 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
276 for (OMPExecutableDirective::filtered_clause_iterator<decltype(CopyinFilter)>
277 I(D.clauses(), CopyinFilter);
278 I; ++I) {
279 auto *C = cast<OMPCopyinClause>(*I);
280 auto IRef = C->varlist_begin();
281 auto ISrcRef = C->source_exprs().begin();
282 auto IDestRef = C->destination_exprs().begin();
283 for (auto *AssignOp : C->assignment_ops()) {
284 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
285 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
286 // Get the address of the master variable.
287 auto *MasterAddr = VD->isStaticLocal()
288 ? CGM.getStaticLocalDeclAddress(VD)
289 : CGM.GetAddrOfGlobal(VD);
290 // Get the address of the threadprivate variable.
291 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
292 if (CopiedVars.size() == 1) {
293 // At first check if current thread is a master thread. If it is, no
294 // need to copy data.
295 CopyBegin = createBasicBlock("copyin.not.master");
296 CopyEnd = createBasicBlock("copyin.not.master.end");
297 Builder.CreateCondBr(
298 Builder.CreateICmpNE(
299 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
300 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
301 CopyBegin, CopyEnd);
302 EmitBlock(CopyBegin);
303 }
304 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
305 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
306 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
307 SrcVD, AssignOp);
308 }
309 ++IRef;
310 ++ISrcRef;
311 ++IDestRef;
312 }
313 }
314 if (CopyEnd) {
315 // Exit out of copying procedure for non-master thread.
316 EmitBlock(CopyEnd, /*IsFinished=*/true);
317 return true;
318 }
319 return false;
320}
321
Alexey Bataev38e89532015-04-16 04:54:05 +0000322bool CodeGenFunction::EmitOMPLastprivateClauseInit(
323 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
324 auto LastprivateFilter = [](const OMPClause *C) -> bool {
325 return C->getClauseKind() == OMPC_lastprivate;
326 };
327 bool HasAtLeastOneLastprivate = false;
328 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
329 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
330 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
331 I; ++I) {
332 auto *C = cast<OMPLastprivateClause>(*I);
333 auto IRef = C->varlist_begin();
334 auto IDestRef = C->destination_exprs().begin();
335 for (auto *IInit : C->private_copies()) {
336 // Keep the address of the original variable for future update at the end
337 // of the loop.
338 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
339 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
340 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
341 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
342 DeclRefExpr DRE(
343 const_cast<VarDecl *>(OrigVD),
344 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
345 OrigVD) != nullptr,
346 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
347 return EmitLValue(&DRE).getAddress();
348 });
349 // Check if the variable is also a firstprivate: in this case IInit is
350 // not generated. Initialization of this variable will happen in codegen
351 // for 'firstprivate' clause.
352 if (!IInit)
353 continue;
354 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
355 bool IsRegistered =
356 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
357 // Emit private VarDecl with copy init.
358 EmitDecl(*VD);
359 return GetAddrOfLocalVar(VD);
360 });
361 assert(IsRegistered && "lastprivate var already registered as private");
362 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
363 }
364 ++IRef, ++IDestRef;
365 }
366 }
367 return HasAtLeastOneLastprivate;
368}
369
370void CodeGenFunction::EmitOMPLastprivateClauseFinal(
371 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
372 // Emit following code:
373 // if (<IsLastIterCond>) {
374 // orig_var1 = private_orig_var1;
375 // ...
376 // orig_varn = private_orig_varn;
377 // }
378 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
379 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
380 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
381 EmitBlock(ThenBB);
382 {
383 auto LastprivateFilter = [](const OMPClause *C) -> bool {
384 return C->getClauseKind() == OMPC_lastprivate;
385 };
386 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
387 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
388 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
389 I; ++I) {
390 auto *C = cast<OMPLastprivateClause>(*I);
391 auto IRef = C->varlist_begin();
392 auto ISrcRef = C->source_exprs().begin();
393 auto IDestRef = C->destination_exprs().begin();
394 for (auto *AssignOp : C->assignment_ops()) {
395 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
396 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
397 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
398 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
399 // Get the address of the original variable.
400 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
401 // Get the address of the private variable.
402 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
403 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
404 DestVD, SrcVD, AssignOp);
405 }
406 ++IRef;
407 ++ISrcRef;
408 ++IDestRef;
409 }
410 }
411 }
412 EmitBlock(DoneBB, /*IsFinished=*/true);
413}
414
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000415void CodeGenFunction::EmitOMPReductionClauseInit(
416 const OMPExecutableDirective &D,
417 CodeGenFunction::OMPPrivateScope &PrivateScope) {
418 auto ReductionFilter = [](const OMPClause *C) -> bool {
419 return C->getClauseKind() == OMPC_reduction;
420 };
421 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
422 ReductionFilter)> I(D.clauses(), ReductionFilter);
423 I; ++I) {
424 auto *C = cast<OMPReductionClause>(*I);
425 auto ILHS = C->lhs_exprs().begin();
426 auto IRHS = C->rhs_exprs().begin();
427 for (auto IRef : C->varlists()) {
428 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
429 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
430 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
431 // Store the address of the original variable associated with the LHS
432 // implicit variable.
433 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
434 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
435 CapturedStmtInfo->lookup(OrigVD) != nullptr,
436 IRef->getType(), VK_LValue, IRef->getExprLoc());
437 return EmitLValue(&DRE).getAddress();
438 });
439 // Emit reduction copy.
440 bool IsRegistered =
441 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
442 // Emit private VarDecl with reduction init.
443 EmitDecl(*PrivateVD);
444 return GetAddrOfLocalVar(PrivateVD);
445 });
446 assert(IsRegistered && "private var already registered as private");
447 // Silence the warning about unused variable.
448 (void)IsRegistered;
449 ++ILHS, ++IRHS;
450 }
451 }
452}
453
454void CodeGenFunction::EmitOMPReductionClauseFinal(
455 const OMPExecutableDirective &D) {
456 llvm::SmallVector<const Expr *, 8> LHSExprs;
457 llvm::SmallVector<const Expr *, 8> RHSExprs;
458 llvm::SmallVector<const Expr *, 8> ReductionOps;
459 auto ReductionFilter = [](const OMPClause *C) -> bool {
460 return C->getClauseKind() == OMPC_reduction;
461 };
462 bool HasAtLeastOneReduction = false;
463 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
464 ReductionFilter)> I(D.clauses(), ReductionFilter);
465 I; ++I) {
466 HasAtLeastOneReduction = true;
467 auto *C = cast<OMPReductionClause>(*I);
468 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
469 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
470 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
471 }
472 if (HasAtLeastOneReduction) {
473 // Emit nowait reduction if nowait clause is present or directive is a
474 // parallel directive (it always has implicit barrier).
475 CGM.getOpenMPRuntime().emitReduction(
476 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
477 D.getSingleClause(OMPC_nowait) ||
478 isOpenMPParallelDirective(D.getDirectiveKind()));
479 }
480}
481
Alexey Bataevb2059782014-10-13 08:23:51 +0000482/// \brief Emits code for OpenMP parallel directive in the parallel region.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000483static void emitOMPParallelCall(CodeGenFunction &CGF,
484 const OMPExecutableDirective &S,
Alexey Bataevb2059782014-10-13 08:23:51 +0000485 llvm::Value *OutlinedFn,
486 llvm::Value *CapturedStruct) {
487 if (auto C = S.getSingleClause(/*K*/ OMPC_num_threads)) {
488 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
489 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
490 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
491 /*IgnoreResultAssign*/ true);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000492 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Alexey Bataevb2059782014-10-13 08:23:51 +0000493 CGF, NumThreads, NumThreadsClause->getLocStart());
494 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000495 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
496 CapturedStruct);
Alexey Bataevb2059782014-10-13 08:23:51 +0000497}
498
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000499static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
500 const OMPExecutableDirective &S,
501 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000502 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000503 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
504 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
505 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000506 if (auto C = S.getSingleClause(/*K*/ OMPC_if)) {
507 auto Cond = cast<OMPIfClause>(C)->getCondition();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000508 EmitOMPIfClause(CGF, Cond, [&](bool ThenBlock) {
Alexey Bataevd74d0602014-10-13 06:02:40 +0000509 if (ThenBlock)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000510 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000511 else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000512 CGF.CGM.getOpenMPRuntime().emitSerialCall(CGF, S.getLocStart(),
513 OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000514 });
Alexey Bataevb2059782014-10-13 08:23:51 +0000515 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000516 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
517}
518
519void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
520 LexicalScope Scope(*this, S.getSourceRange());
521 // Emit parallel region as a standalone region.
522 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
523 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000524 bool Copyins = CGF.EmitOMPCopyinClause(S);
525 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
526 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000527 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 // initialization of firstprivate variables or propagation master's thread
529 // values of threadprivate variables to local instances of that variables
530 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000531 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
532 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000533 }
534 CGF.EmitOMPPrivateClause(S, PrivateScope);
535 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
536 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000537 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000538 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000539 // Emit implicit barrier at the end of the 'parallel' directive.
540 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
541 OMPD_unknown);
542 };
543 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000544}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000545
Alexander Musmand196ef22014-10-07 08:57:09 +0000546void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000547 bool SeparateIter) {
548 RunCleanupsScope BodyScope(*this);
549 // Update counters values on current iteration.
550 for (auto I : S.updates()) {
551 EmitIgnoredExpr(I);
552 }
Alexander Musman3276a272015-03-21 10:12:56 +0000553 // Update the linear variables.
554 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
555 for (auto U : C->updates()) {
556 EmitIgnoredExpr(U);
557 }
558 }
559
Alexander Musmana5f070a2014-10-01 06:03:56 +0000560 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000561 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000562 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
563 // Emit loop body.
564 EmitStmt(S.getBody());
565 // The end (updates/cleanups).
566 EmitBlock(Continue.getBlock());
567 BreakContinueStack.pop_back();
568 if (SeparateIter) {
569 // TODO: Update lastprivates if the SeparateIter flag is true.
570 // This will be implemented in a follow-up OMPLastprivateClause patch, but
571 // result should be still correct without it, as we do not make these
572 // variables private yet.
573 }
574}
575
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000576void CodeGenFunction::EmitOMPInnerLoop(
577 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
578 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000579 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
580 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000581 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000582 auto Cnt = getPGORegionCounter(&S);
583
584 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000585 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000586 EmitBlock(CondBlock);
587 LoopStack.push(CondBlock);
588
589 // If there are any cleanups between here and the loop-exit scope,
590 // create a block to stage a loop exit along.
591 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000592 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000593 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000594
Alexander Musmand196ef22014-10-07 08:57:09 +0000595 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000596
Alexey Bataev2df54a02015-03-12 08:53:29 +0000597 // Emit condition.
598 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, Cnt.getCount());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000599 if (ExitBlock != LoopExit.getBlock()) {
600 EmitBlock(ExitBlock);
601 EmitBranchThroughCleanup(LoopExit);
602 }
603
604 EmitBlock(LoopBody);
605 Cnt.beginRegion(Builder);
606
607 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000608 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000609 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
610
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000611 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000612
613 // Emit "IV = IV + 1" and a back-edge to the condition block.
614 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000615 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000616 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000617 BreakContinueStack.pop_back();
618 EmitBranch(CondBlock);
619 LoopStack.pop();
620 // Emit the fall-through block.
621 EmitBlock(LoopExit.getBlock());
622}
623
624void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
625 auto IC = S.counters().begin();
626 for (auto F : S.finals()) {
627 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
628 EmitIgnoredExpr(F);
629 }
630 ++IC;
631 }
Alexander Musman3276a272015-03-21 10:12:56 +0000632 // Emit the final values of the linear variables.
633 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
634 for (auto F : C->finals()) {
635 EmitIgnoredExpr(F);
636 }
637 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000638}
639
Alexander Musman09184fe2014-09-30 05:29:28 +0000640static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
641 const OMPAlignedClause &Clause) {
642 unsigned ClauseAlignment = 0;
643 if (auto AlignmentExpr = Clause.getAlignment()) {
644 auto AlignmentCI =
645 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
646 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
647 }
648 for (auto E : Clause.varlists()) {
649 unsigned Alignment = ClauseAlignment;
650 if (Alignment == 0) {
651 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000652 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000653 // alignments for SIMD instructions on the target platforms are assumed.
654 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
655 E->getType());
656 }
657 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
658 "alignment is not power of 2");
659 if (Alignment != 0) {
660 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
661 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
662 }
663 }
664}
665
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000666static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
667 CodeGenFunction::OMPPrivateScope &LoopScope,
668 ArrayRef<Expr *> Counters) {
669 for (auto *E : Counters) {
670 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
671 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
672 // Emit var without initialization.
673 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
674 CGF.EmitAutoVarCleanups(VarEmission);
675 return VarEmission.getAllocatedAddress();
676 });
677 assert(IsRegistered && "counter already registered as private");
678 // Silence the warning about unused variable.
679 (void)IsRegistered;
680 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000681}
682
Alexey Bataev62dbb972015-04-22 11:59:37 +0000683static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
684 const Expr *Cond, llvm::BasicBlock *TrueBlock,
685 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
686 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
687 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
688 const VarDecl *IVDecl =
689 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
690 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
691 // Emit var without initialization.
692 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
693 CGF.EmitAutoVarCleanups(VarEmission);
694 return VarEmission.getAllocatedAddress();
695 });
696 assert(IsRegistered && "counter already registered as private");
697 // Silence the warning about unused variable.
698 (void)IsRegistered;
699 (void)PreCondScope.Privatize();
700 // Initialize internal counter to 0 to calculate initial values of real
701 // counters.
702 LValue IV = CGF.EmitLValue(S.getIterationVariable());
703 CGF.EmitStoreOfScalar(
704 llvm::ConstantInt::getNullValue(
705 IV.getAddress()->getType()->getPointerElementType()),
706 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
707 // Get initial values of real counters.
708 for (auto I : S.updates()) {
709 CGF.EmitIgnoredExpr(I);
710 }
711 // Check that loop is executed at least one time.
712 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
713}
714
Alexander Musman3276a272015-03-21 10:12:56 +0000715static void
716EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
717 CodeGenFunction::OMPPrivateScope &PrivateScope) {
718 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
719 for (auto *E : Clause->varlists()) {
720 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
721 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
722 // Emit var without initialization.
723 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
724 CGF.EmitAutoVarCleanups(VarEmission);
725 return VarEmission.getAllocatedAddress();
726 });
727 assert(IsRegistered && "linear var already registered as private");
728 // Silence the warning about unused variable.
729 (void)IsRegistered;
730 }
731 }
732}
733
Alexander Musman515ad8c2014-05-22 08:54:05 +0000734void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000735 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
736 // Pragma 'simd' code depends on presence of 'lastprivate'.
737 // If present, we have to separate last iteration of the loop:
738 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000739 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000740 // for (IV in 0..LastIteration-1) BODY;
741 // BODY with updates of lastprivate vars;
742 // <Final counter/linear vars updates>;
743 // }
744 //
745 // otherwise (when there's no lastprivate):
746 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000747 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000748 // for (IV in 0..LastIteration) BODY;
749 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000750 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000751 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000752
Alexey Bataev62dbb972015-04-22 11:59:37 +0000753 // Emit: if (PreCond) - begin.
754 // If the condition constant folds and can be elided, avoid emitting the
755 // whole loop.
756 bool CondConstant;
757 llvm::BasicBlock *ContBlock = nullptr;
758 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
759 if (!CondConstant)
760 return;
761 } else {
762 RegionCounter Cnt = CGF.getPGORegionCounter(&S);
763 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
764 ContBlock = CGF.createBasicBlock("simd.if.end");
765 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
766 CGF.EmitBlock(ThenBlock);
767 Cnt.beginRegion(CGF.Builder);
768 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000769 // Walk clauses and process safelen/lastprivate.
770 bool SeparateIter = false;
771 CGF.LoopStack.setParallel();
772 CGF.LoopStack.setVectorizerEnable(true);
773 for (auto C : S.clauses()) {
774 switch (C->getClauseKind()) {
775 case OMPC_safelen: {
776 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
777 AggValueSlot::ignored(), true);
778 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
779 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
780 // In presence of finite 'safelen', it may be unsafe to mark all
781 // the memory instructions parallel, because loop-carried
782 // dependences of 'safelen' iterations are possible.
783 CGF.LoopStack.setParallel(false);
784 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000785 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000786 case OMPC_aligned:
787 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
788 break;
789 case OMPC_lastprivate:
790 SeparateIter = true;
791 break;
792 default:
793 // Not handled yet
794 ;
795 }
796 }
Alexander Musman3276a272015-03-21 10:12:56 +0000797
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798 // Emit inits for the linear variables.
799 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
800 for (auto Init : C->inits()) {
801 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
802 CGF.EmitVarDecl(*D);
803 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000804 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000805
806 // Emit the loop iteration variable.
807 const Expr *IVExpr = S.getIterationVariable();
808 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
809 CGF.EmitVarDecl(*IVDecl);
810 CGF.EmitIgnoredExpr(S.getInit());
811
812 // Emit the iterations count variable.
813 // If it is not a variable, Sema decided to calculate iterations count on
814 // each
815 // iteration (e.g., it is foldable into a constant).
816 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
817 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
818 // Emit calculation of the iterations count.
819 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000820 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000821
822 // Emit the linear steps for the linear clauses.
823 // If a step is not constant, it is pre-calculated before the loop.
824 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
825 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
826 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
827 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
828 // Emit calculation of the linear step.
829 CGF.EmitIgnoredExpr(CS);
830 }
831 }
832
Alexey Bataev62dbb972015-04-22 11:59:37 +0000833 {
834 OMPPrivateScope LoopScope(CGF);
835 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
836 EmitPrivateLinearVars(CGF, S, LoopScope);
837 CGF.EmitOMPPrivateClause(S, LoopScope);
838 (void)LoopScope.Privatize();
839 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
840 S.getCond(SeparateIter), S.getInc(),
841 [&S](CodeGenFunction &CGF) {
842 CGF.EmitOMPLoopBody(S);
843 CGF.EmitStopPoint(&S);
844 },
845 [](CodeGenFunction &) {});
846 if (SeparateIter) {
847 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000848 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000849 }
850 CGF.EmitOMPSimdFinal(S);
851 // Emit: if (PreCond) - end.
852 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000853 CGF.EmitBranch(ContBlock);
854 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000855 }
856 };
857 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000858}
859
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000860void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
861 const OMPLoopDirective &S,
862 OMPPrivateScope &LoopScope,
863 llvm::Value *LB, llvm::Value *UB,
864 llvm::Value *ST, llvm::Value *IL,
865 llvm::Value *Chunk) {
866 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000867
868 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
869 const bool Dynamic = RT.isDynamic(ScheduleKind);
870
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000871 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
872 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000873
874 // Emit outer loop.
875 //
876 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000877 // When schedule(dynamic,chunk_size) is specified, the iterations are
878 // distributed to threads in the team in chunks as the threads request them.
879 // Each thread executes a chunk of iterations, then requests another chunk,
880 // until no chunks remain to be distributed. Each chunk contains chunk_size
881 // iterations, except for the last chunk to be distributed, which may have
882 // fewer iterations. When no chunk_size is specified, it defaults to 1.
883 //
884 // When schedule(guided,chunk_size) is specified, the iterations are assigned
885 // to threads in the team in chunks as the executing threads request them.
886 // Each thread executes a chunk of iterations, then requests another chunk,
887 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
888 // each chunk is proportional to the number of unassigned iterations divided
889 // by the number of threads in the team, decreasing to 1. For a chunk_size
890 // with value k (greater than 1), the size of each chunk is determined in the
891 // same way, with the restriction that the chunks do not contain fewer than k
892 // iterations (except for the last chunk to be assigned, which may have fewer
893 // than k iterations).
894 //
895 // When schedule(auto) is specified, the decision regarding scheduling is
896 // delegated to the compiler and/or runtime system. The programmer gives the
897 // implementation the freedom to choose any possible mapping of iterations to
898 // threads in the team.
899 //
900 // When schedule(runtime) is specified, the decision regarding scheduling is
901 // deferred until run time, and the schedule and chunk size are taken from the
902 // run-sched-var ICV. If the ICV is set to auto, the schedule is
903 // implementation defined
904 //
905 // while(__kmpc_dispatch_next(&LB, &UB)) {
906 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000907 // while (idx <= UB) { BODY; ++idx;
908 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
909 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 // }
911 //
912 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000913 // When schedule(static, chunk_size) is specified, iterations are divided into
914 // chunks of size chunk_size, and the chunks are assigned to the threads in
915 // the team in a round-robin fashion in the order of the thread number.
916 //
917 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
918 // while (idx <= UB) { BODY; ++idx; } // inner loop
919 // LB = LB + ST;
920 // UB = UB + ST;
921 // }
922 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000923
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000924 const Expr *IVExpr = S.getIterationVariable();
925 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
926 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
927
Alexander Musman92bdaab2015-03-12 13:37:50 +0000928 RT.emitForInit(
929 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
930 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
931 Chunk);
932
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000933 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
934
935 // Start the loop with a block that tests the condition.
936 auto CondBlock = createBasicBlock("omp.dispatch.cond");
937 EmitBlock(CondBlock);
938 LoopStack.push(CondBlock);
939
940 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000941 if (!Dynamic) {
942 // UB = min(UB, GlobalUB)
943 EmitIgnoredExpr(S.getEnsureUpperBound());
944 // IV = LB
945 EmitIgnoredExpr(S.getInit());
946 // IV < UB
947 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
948 } else {
949 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
950 IL, LB, UB, ST);
951 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000952
953 // If there are any cleanups between here and the loop-exit scope,
954 // create a block to stage a loop exit along.
955 auto ExitBlock = LoopExit.getBlock();
956 if (LoopScope.requiresCleanups())
957 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
958
959 auto LoopBody = createBasicBlock("omp.dispatch.body");
960 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
961 if (ExitBlock != LoopExit.getBlock()) {
962 EmitBlock(ExitBlock);
963 EmitBranchThroughCleanup(LoopExit);
964 }
965 EmitBlock(LoopBody);
966
Alexander Musman92bdaab2015-03-12 13:37:50 +0000967 // Emit "IV = LB" (in case of static schedule, we have already calculated new
968 // LB for loop condition and emitted it above).
969 if (Dynamic)
970 EmitIgnoredExpr(S.getInit());
971
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000972 // Create a block for the increment.
973 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
974 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
975
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000976 bool DynamicWithOrderedClause =
977 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
978 SourceLocation Loc = S.getLocStart();
979 EmitOMPInnerLoop(
980 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
981 S.getInc(),
982 [&S](CodeGenFunction &CGF) {
983 CGF.EmitOMPLoopBody(S);
984 CGF.EmitStopPoint(&S);
985 },
986 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
987 if (DynamicWithOrderedClause) {
988 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
989 CGF, Loc, IVSize, IVSigned);
990 }
991 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000992
993 EmitBlock(Continue.getBlock());
994 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000995 if (!Dynamic) {
996 // Emit "LB = LB + Stride", "UB = UB + Stride".
997 EmitIgnoredExpr(S.getNextLowerBound());
998 EmitIgnoredExpr(S.getNextUpperBound());
999 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001000
1001 EmitBranch(CondBlock);
1002 LoopStack.pop();
1003 // Emit the fall-through block.
1004 EmitBlock(LoopExit.getBlock());
1005
1006 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001007 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001008 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001009}
1010
Alexander Musmanc6388682014-12-15 07:07:06 +00001011/// \brief Emit a helper variable and return corresponding lvalue.
1012static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1013 const DeclRefExpr *Helper) {
1014 auto VDecl = cast<VarDecl>(Helper->getDecl());
1015 CGF.EmitVarDecl(*VDecl);
1016 return CGF.EmitLValue(Helper);
1017}
1018
Alexey Bataev38e89532015-04-16 04:54:05 +00001019bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001020 // Emit the loop iteration variable.
1021 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1022 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1023 EmitVarDecl(*IVDecl);
1024
1025 // Emit the iterations count variable.
1026 // If it is not a variable, Sema decided to calculate iterations count on each
1027 // iteration (e.g., it is foldable into a constant).
1028 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1029 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1030 // Emit calculation of the iterations count.
1031 EmitIgnoredExpr(S.getCalcLastIteration());
1032 }
1033
1034 auto &RT = CGM.getOpenMPRuntime();
1035
Alexey Bataev38e89532015-04-16 04:54:05 +00001036 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001037 // Check pre-condition.
1038 {
1039 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001040 // If the condition constant folds and can be elided, avoid emitting the
1041 // whole loop.
1042 bool CondConstant;
1043 llvm::BasicBlock *ContBlock = nullptr;
1044 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1045 if (!CondConstant)
1046 return false;
1047 } else {
1048 RegionCounter Cnt = getPGORegionCounter(&S);
1049 auto *ThenBlock = createBasicBlock("omp.precond.then");
1050 ContBlock = createBasicBlock("omp.precond.end");
1051 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
1052 Cnt.getCount());
1053 EmitBlock(ThenBlock);
1054 Cnt.beginRegion(Builder);
1055 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001056 // Emit 'then' code.
1057 {
1058 // Emit helper vars inits.
1059 LValue LB =
1060 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1061 LValue UB =
1062 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1063 LValue ST =
1064 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1065 LValue IL =
1066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1067
1068 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001069 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1070 // Emit implicit barrier to synchronize threads and avoid data races on
1071 // initialization of firstprivate variables.
1072 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1073 OMPD_unknown);
1074 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001075 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001076 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001077 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001078
1079 // Detect the loop schedule kind and chunk.
1080 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1081 llvm::Value *Chunk = nullptr;
1082 if (auto C = cast_or_null<OMPScheduleClause>(
1083 S.getSingleClause(OMPC_schedule))) {
1084 ScheduleKind = C->getScheduleKind();
1085 if (auto Ch = C->getChunkSize()) {
1086 Chunk = EmitScalarExpr(Ch);
1087 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1088 S.getIterationVariable()->getType());
1089 }
1090 }
1091 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1092 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1093 if (RT.isStaticNonchunked(ScheduleKind,
1094 /* Chunked */ Chunk != nullptr)) {
1095 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1096 // When no chunk_size is specified, the iteration space is divided into
1097 // chunks that are approximately equal in size, and at most one chunk is
1098 // distributed to each thread. Note that the size of the chunks is
1099 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001100 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1101 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1102 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001103 // UB = min(UB, GlobalUB);
1104 EmitIgnoredExpr(S.getEnsureUpperBound());
1105 // IV = LB;
1106 EmitIgnoredExpr(S.getInit());
1107 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001108 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1109 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001110 [&S](CodeGenFunction &CGF) {
1111 CGF.EmitOMPLoopBody(S);
1112 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001113 },
1114 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001115 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001116 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001117 } else {
1118 // Emit the outer loop, which requests its work chunk [LB..UB] from
1119 // runtime and runs the inner loop to process it.
1120 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1121 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1122 Chunk);
1123 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001124 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1125 if (HasLastprivateClause)
1126 EmitOMPLastprivateClauseFinal(
1127 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001128 }
1129 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001130 if (ContBlock) {
1131 EmitBranch(ContBlock);
1132 EmitBlock(ContBlock, true);
1133 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001134 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001135 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001136}
1137
1138void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001139 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001140 bool HasLastprivates = false;
1141 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1142 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1143 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001144 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001145
1146 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001147 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001148 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1149 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001150}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001151
Alexander Musmanf82886e2014-09-18 05:12:34 +00001152void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1153 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1154}
1155
Alexey Bataev2df54a02015-03-12 08:53:29 +00001156static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1157 const Twine &Name,
1158 llvm::Value *Init = nullptr) {
1159 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1160 if (Init)
1161 CGF.EmitScalarInit(Init, LVal);
1162 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001163}
1164
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001165static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1166 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001167 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1168 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1169 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
1171 auto &C = CGF.CGM.getContext();
1172 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1173 // Emit helper vars inits.
1174 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1175 CGF.Builder.getInt32(0));
1176 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1177 LValue UB =
1178 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1179 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1180 CGF.Builder.getInt32(1));
1181 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1182 CGF.Builder.getInt32(0));
1183 // Loop counter.
1184 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1185 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001186 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001188 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // Generate condition for loop.
1190 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1191 OK_Ordinary, S.getLocStart(),
1192 /*fpContractable=*/false);
1193 // Increment for loop counter.
1194 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1195 OK_Ordinary, S.getLocStart());
1196 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1197 // Iterate through all sections and emit a switch construct:
1198 // switch (IV) {
1199 // case 0:
1200 // <SectionStmt[0]>;
1201 // break;
1202 // ...
1203 // case <NumSection> - 1:
1204 // <SectionStmt[<NumSection> - 1]>;
1205 // break;
1206 // }
1207 // .omp.sections.exit:
1208 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1209 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1210 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1211 CS->size());
1212 unsigned CaseNumber = 0;
1213 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1214 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1215 CGF.EmitBlock(CaseBB);
1216 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1217 CGF.EmitStmt(*C);
1218 CGF.EmitBranch(ExitBB);
1219 }
1220 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1221 };
1222 // Emit static non-chunked loop.
1223 CGF.CGM.getOpenMPRuntime().emitForInit(
1224 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1225 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1226 ST.getAddress());
1227 // UB = min(UB, GlobalUB);
1228 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1229 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1230 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1231 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1232 // IV = LB;
1233 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1234 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001235 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1236 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001237 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001238 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001239 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001240
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001241 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1242 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001243 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001244 // If only one section is found - no need to generate loop, emit as a single
1245 // region.
1246 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
1247 CGF.EmitStmt(Stmt);
1248 CGF.EnsureInsertPoint();
1249 };
1250 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1251 llvm::None, llvm::None,
1252 llvm::None, llvm::None);
1253 return OMPD_single;
1254}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001255
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001256void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1257 LexicalScope Scope(*this, S.getSourceRange());
1258 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001259 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001260 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001261 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001262 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001263}
1264
1265void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266 LexicalScope Scope(*this, S.getSourceRange());
1267 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1268 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1269 CGF.EnsureInsertPoint();
1270 };
1271 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001272}
1273
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001274void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001275 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001276 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001277 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001278 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001279 // Check if there are any 'copyprivate' clauses associated with this
1280 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001281 // construct.
1282 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1283 return C->getClauseKind() == OMPC_copyprivate;
1284 };
1285 // Build a list of copyprivate variables along with helper expressions
1286 // (<source>, <destination>, <destination>=<source> expressions)
1287 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1288 CopyprivateFilter)> CopyprivateIter;
1289 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1290 auto *C = cast<OMPCopyprivateClause>(*I);
1291 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001292 DestExprs.append(C->destination_exprs().begin(),
1293 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001294 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001295 AssignmentOps.append(C->assignment_ops().begin(),
1296 C->assignment_ops().end());
1297 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001298 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001299 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001300 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1301 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1302 CGF.EnsureInsertPoint();
1303 };
1304 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001305 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001306 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001307 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001308 if (!S.getSingleClause(OMPC_nowait)) {
1309 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1310 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001311}
1312
Alexey Bataev8d690652014-12-04 07:23:53 +00001313void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314 LexicalScope Scope(*this, S.getSourceRange());
1315 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1316 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1317 CGF.EnsureInsertPoint();
1318 };
1319 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001320}
1321
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001322void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323 LexicalScope Scope(*this, S.getSourceRange());
1324 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1325 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1326 CGF.EnsureInsertPoint();
1327 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001328 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001329 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001330}
1331
Alexey Bataev671605e2015-04-13 05:28:11 +00001332void CodeGenFunction::EmitOMPParallelForDirective(
1333 const OMPParallelForDirective &S) {
1334 // Emit directive as a combined directive that consists of two implicit
1335 // directives: 'parallel' with 'for' directive.
1336 LexicalScope Scope(*this, S.getSourceRange());
1337 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1338 CGF.EmitOMPWorksharingLoop(S);
1339 // Emit implicit barrier at the end of parallel region, but this barrier
1340 // is at the end of 'for' directive, so emit it as the implicit barrier for
1341 // this 'for' directive.
1342 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1343 OMPD_parallel);
1344 };
1345 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001346}
1347
Alexander Musmane4e893b2014-09-23 09:33:00 +00001348void CodeGenFunction::EmitOMPParallelForSimdDirective(
1349 const OMPParallelForSimdDirective &) {
1350 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1351}
1352
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001353void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001354 const OMPParallelSectionsDirective &S) {
1355 // Emit directive as a combined directive that consists of two implicit
1356 // directives: 'parallel' with 'sections' directive.
1357 LexicalScope Scope(*this, S.getSourceRange());
1358 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1359 (void)emitSections(CGF, S);
1360 // Emit implicit barrier at the end of parallel region.
1361 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1362 OMPD_parallel);
1363 };
1364 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001365}
1366
Alexey Bataev62b63b12015-03-10 07:28:44 +00001367void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1368 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001369 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001370 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1371 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1372 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001373 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001374 // The first function argument for tasks is a thread id, the second one is a
1375 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001376 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1377 if (*PartId) {
1378 // TODO: emit code for untied tasks.
1379 }
1380 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1381 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001382 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001383 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001384 // Check if we should emit tied or untied task.
1385 bool Tied = !S.getSingleClause(OMPC_untied);
1386 // Check if the task is final
1387 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1388 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1389 // If the condition constant folds and can be elided, try to avoid emitting
1390 // the condition and the dead arm of the if/else.
1391 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1392 bool CondConstant;
1393 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1394 Final.setInt(CondConstant);
1395 else
1396 Final.setPointer(EvaluateExprAsBool(Cond));
1397 } else {
1398 // By default the task is not final.
1399 Final.setInt(/*IntVal=*/false);
1400 }
1401 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
1402 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
1403 OutlinedFn, SharedsTy, CapturedStruct);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001404}
1405
Alexey Bataev9f797f32015-02-05 05:57:51 +00001406void CodeGenFunction::EmitOMPTaskyieldDirective(
1407 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001408 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001409}
1410
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001411void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001412 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001413}
1414
Alexey Bataev2df347a2014-07-18 10:17:07 +00001415void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1416 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1417}
1418
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001419void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001420 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1421 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1422 auto FlushClause = cast<OMPFlushClause>(C);
1423 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1424 FlushClause->varlist_end());
1425 }
1426 return llvm::None;
1427 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001428}
1429
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001430void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1431 LexicalScope Scope(*this, S.getSourceRange());
1432 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1433 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1434 CGF.EnsureInsertPoint();
1435 };
1436 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001437}
1438
Alexey Bataevb57056f2015-01-22 06:17:56 +00001439static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1440 QualType SrcType, QualType DestType) {
1441 assert(CGF.hasScalarEvaluationKind(DestType) &&
1442 "DestType must have scalar evaluation kind.");
1443 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1444 return Val.isScalar()
1445 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1446 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1447 DestType);
1448}
1449
1450static CodeGenFunction::ComplexPairTy
1451convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1452 QualType DestType) {
1453 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1454 "DestType must have complex evaluation kind.");
1455 CodeGenFunction::ComplexPairTy ComplexVal;
1456 if (Val.isScalar()) {
1457 // Convert the input element to the element type of the complex.
1458 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1459 auto ScalarVal =
1460 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1461 ComplexVal = CodeGenFunction::ComplexPairTy(
1462 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1463 } else {
1464 assert(Val.isComplex() && "Must be a scalar or complex.");
1465 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1466 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1467 ComplexVal.first = CGF.EmitScalarConversion(
1468 Val.getComplexVal().first, SrcElementType, DestElementType);
1469 ComplexVal.second = CGF.EmitScalarConversion(
1470 Val.getComplexVal().second, SrcElementType, DestElementType);
1471 }
1472 return ComplexVal;
1473}
1474
1475static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1476 const Expr *X, const Expr *V,
1477 SourceLocation Loc) {
1478 // v = x;
1479 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1480 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1481 LValue XLValue = CGF.EmitLValue(X);
1482 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001483 RValue Res = XLValue.isGlobalReg()
1484 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1485 : CGF.EmitAtomicLoad(XLValue, Loc,
1486 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001487 : llvm::Monotonic,
1488 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001489 // OpenMP, 2.12.6, atomic Construct
1490 // Any atomic construct with a seq_cst clause forces the atomically
1491 // performed operation to include an implicit flush operation without a
1492 // list.
1493 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001494 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001495 switch (CGF.getEvaluationKind(V->getType())) {
1496 case TEK_Scalar:
1497 CGF.EmitStoreOfScalar(
1498 convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
1499 break;
1500 case TEK_Complex:
1501 CGF.EmitStoreOfComplex(
1502 convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
1503 /*isInit=*/false);
1504 break;
1505 case TEK_Aggregate:
1506 llvm_unreachable("Must be a scalar or complex.");
1507 }
1508}
1509
Alexey Bataevb8329262015-02-27 06:33:30 +00001510static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1511 const Expr *X, const Expr *E,
1512 SourceLocation Loc) {
1513 // x = expr;
1514 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
1515 LValue XLValue = CGF.EmitLValue(X);
1516 RValue ExprRValue = CGF.EmitAnyExpr(E);
1517 if (XLValue.isGlobalReg())
1518 CGF.EmitStoreThroughGlobalRegLValue(ExprRValue, XLValue);
1519 else
1520 CGF.EmitAtomicStore(ExprRValue, XLValue,
1521 IsSeqCst ? llvm::SequentiallyConsistent
1522 : llvm::Monotonic,
1523 XLValue.isVolatile(), /*IsInit=*/false);
1524 // OpenMP, 2.12.6, atomic Construct
1525 // Any atomic construct with a seq_cst clause forces the atomically
1526 // performed operation to include an implicit flush operation without a
1527 // list.
1528 if (IsSeqCst)
1529 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1530}
1531
Benjamin Kramer5df7c1a2015-04-18 10:00:10 +00001532static bool emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update,
1533 BinaryOperatorKind BO, llvm::AtomicOrdering AO,
1534 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001535 auto &Context = CGF.CGM.getContext();
1536 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001537 // expression is simple and atomic is allowed for the given type for the
1538 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001539 if (BO == BO_Comma || !Update.isScalar() ||
1540 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1541 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1542 (Update.getScalarVal()->getType() !=
1543 X.getAddress()->getType()->getPointerElementType())) ||
1544 !Context.getTargetInfo().hasBuiltinAtomic(
1545 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
1546 return false;
1547
1548 llvm::AtomicRMWInst::BinOp RMWOp;
1549 switch (BO) {
1550 case BO_Add:
1551 RMWOp = llvm::AtomicRMWInst::Add;
1552 break;
1553 case BO_Sub:
1554 if (!IsXLHSInRHSPart)
1555 return false;
1556 RMWOp = llvm::AtomicRMWInst::Sub;
1557 break;
1558 case BO_And:
1559 RMWOp = llvm::AtomicRMWInst::And;
1560 break;
1561 case BO_Or:
1562 RMWOp = llvm::AtomicRMWInst::Or;
1563 break;
1564 case BO_Xor:
1565 RMWOp = llvm::AtomicRMWInst::Xor;
1566 break;
1567 case BO_LT:
1568 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1569 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1570 : llvm::AtomicRMWInst::Max)
1571 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1572 : llvm::AtomicRMWInst::UMax);
1573 break;
1574 case BO_GT:
1575 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1576 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1577 : llvm::AtomicRMWInst::Min)
1578 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1579 : llvm::AtomicRMWInst::UMin);
1580 break;
1581 case BO_Mul:
1582 case BO_Div:
1583 case BO_Rem:
1584 case BO_Shl:
1585 case BO_Shr:
1586 case BO_LAnd:
1587 case BO_LOr:
1588 return false;
1589 case BO_PtrMemD:
1590 case BO_PtrMemI:
1591 case BO_LE:
1592 case BO_GE:
1593 case BO_EQ:
1594 case BO_NE:
1595 case BO_Assign:
1596 case BO_AddAssign:
1597 case BO_SubAssign:
1598 case BO_AndAssign:
1599 case BO_OrAssign:
1600 case BO_XorAssign:
1601 case BO_MulAssign:
1602 case BO_DivAssign:
1603 case BO_RemAssign:
1604 case BO_ShlAssign:
1605 case BO_ShrAssign:
1606 case BO_Comma:
1607 llvm_unreachable("Unsupported atomic update operation");
1608 }
1609 auto *UpdateVal = Update.getScalarVal();
1610 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1611 UpdateVal = CGF.Builder.CreateIntCast(
1612 IC, X.getAddress()->getType()->getPointerElementType(),
1613 X.getType()->hasSignedIntegerRepresentation());
1614 }
1615 CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1616 return true;
1617}
1618
1619void CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
1620 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1621 llvm::AtomicOrdering AO, SourceLocation Loc,
1622 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1623 // Update expressions are allowed to have the following forms:
1624 // x binop= expr; -> xrval + expr;
1625 // x++, ++x -> xrval + 1;
1626 // x--, --x -> xrval - 1;
1627 // x = x binop expr; -> xrval binop expr
1628 // x = expr Op x; - > expr binop xrval;
1629 if (!emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart)) {
1630 if (X.isGlobalReg()) {
1631 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1632 // 'xrval'.
1633 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1634 } else {
1635 // Perform compare-and-swap procedure.
1636 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001637 }
1638 }
Alexey Bataevb4505a72015-03-30 05:20:59 +00001639}
1640
1641static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1642 const Expr *X, const Expr *E,
1643 const Expr *UE, bool IsXLHSInRHSPart,
1644 SourceLocation Loc) {
1645 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1646 "Update expr in 'atomic update' must be a binary operator.");
1647 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1648 // Update expressions are allowed to have the following forms:
1649 // x binop= expr; -> xrval + expr;
1650 // x++, ++x -> xrval + 1;
1651 // x--, --x -> xrval - 1;
1652 // x = x binop expr; -> xrval binop expr
1653 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001654 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001655 LValue XLValue = CGF.EmitLValue(X);
1656 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001657 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001658 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1659 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1660 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1661 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1662 auto Gen =
1663 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1664 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1665 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1666 return CGF.EmitAnyExpr(UE);
1667 };
1668 CGF.EmitOMPAtomicSimpleUpdateExpr(XLValue, ExprRValue, BOUE->getOpcode(),
1669 IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001670 // OpenMP, 2.12.6, atomic Construct
1671 // Any atomic construct with a seq_cst clause forces the atomically
1672 // performed operation to include an implicit flush operation without a
1673 // list.
1674 if (IsSeqCst)
1675 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1676}
1677
Alexey Bataevb57056f2015-01-22 06:17:56 +00001678static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
1679 bool IsSeqCst, const Expr *X, const Expr *V,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001680 const Expr *E, const Expr *UE,
1681 bool IsXLHSInRHSPart, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001682 switch (Kind) {
1683 case OMPC_read:
1684 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1685 break;
1686 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001687 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1688 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001689 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001690 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001691 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1692 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001693 case OMPC_capture:
1694 llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
1695 case OMPC_if:
1696 case OMPC_final:
1697 case OMPC_num_threads:
1698 case OMPC_private:
1699 case OMPC_firstprivate:
1700 case OMPC_lastprivate:
1701 case OMPC_reduction:
1702 case OMPC_safelen:
1703 case OMPC_collapse:
1704 case OMPC_default:
1705 case OMPC_seq_cst:
1706 case OMPC_shared:
1707 case OMPC_linear:
1708 case OMPC_aligned:
1709 case OMPC_copyin:
1710 case OMPC_copyprivate:
1711 case OMPC_flush:
1712 case OMPC_proc_bind:
1713 case OMPC_schedule:
1714 case OMPC_ordered:
1715 case OMPC_nowait:
1716 case OMPC_untied:
1717 case OMPC_threadprivate:
1718 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001719 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1720 }
1721}
1722
1723void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1724 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1725 OpenMPClauseKind Kind = OMPC_unknown;
1726 for (auto *C : S.clauses()) {
1727 // Find first clause (skip seq_cst clause, if it is first).
1728 if (C->getClauseKind() != OMPC_seq_cst) {
1729 Kind = C->getClauseKind();
1730 break;
1731 }
1732 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001733
1734 const auto *CS =
1735 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
1736 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
1737 enterFullExpression(EWC);
Alexey Bataev10fec572015-03-11 04:48:56 +00001738
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001739 LexicalScope Scope(*this, S.getSourceRange());
1740 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
1741 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
1742 S.getUpdateExpr(), S.isXLHSInRHSPart(), S.getLocStart());
1743 };
1744 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001745}
1746
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001747void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1748 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1749}
1750
Alexey Bataev13314bf2014-10-09 04:18:56 +00001751void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1752 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1753}
1754