blob: 744f9142db213ae72d713ab42c1536f261c129fd [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 };
Alexey Bataev50a64582015-04-22 12:24:45 +0000245 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000246 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
Alexey Bataev50a64582015-04-22 12:24:45 +0000247 I(D.clauses(), PrivateFilter);
248 I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000249 auto *C = cast<OMPPrivateClause>(*I);
250 auto IRef = C->varlist_begin();
251 for (auto IInit : C->private_copies()) {
252 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000253 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
254 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
255 bool IsRegistered =
256 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
257 // Emit private VarDecl with copy init.
258 EmitDecl(*VD);
259 return GetAddrOfLocalVar(VD);
260 });
261 assert(IsRegistered && "private var already registered as private");
262 // Silence the warning about unused variable.
263 (void)IsRegistered;
264 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000265 ++IRef;
266 }
267 }
268}
269
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000270bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
271 // threadprivate_var1 = master_threadprivate_var1;
272 // operator=(threadprivate_var2, master_threadprivate_var2);
273 // ...
274 // __kmpc_barrier(&loc, global_tid);
275 auto CopyinFilter = [](const OMPClause *C) -> bool {
276 return C->getClauseKind() == OMPC_copyin;
277 };
278 llvm::DenseSet<const VarDecl *> CopiedVars;
279 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
280 for (OMPExecutableDirective::filtered_clause_iterator<decltype(CopyinFilter)>
281 I(D.clauses(), CopyinFilter);
282 I; ++I) {
283 auto *C = cast<OMPCopyinClause>(*I);
284 auto IRef = C->varlist_begin();
285 auto ISrcRef = C->source_exprs().begin();
286 auto IDestRef = C->destination_exprs().begin();
287 for (auto *AssignOp : C->assignment_ops()) {
288 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
289 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
290 // Get the address of the master variable.
291 auto *MasterAddr = VD->isStaticLocal()
292 ? CGM.getStaticLocalDeclAddress(VD)
293 : CGM.GetAddrOfGlobal(VD);
294 // Get the address of the threadprivate variable.
295 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
296 if (CopiedVars.size() == 1) {
297 // At first check if current thread is a master thread. If it is, no
298 // need to copy data.
299 CopyBegin = createBasicBlock("copyin.not.master");
300 CopyEnd = createBasicBlock("copyin.not.master.end");
301 Builder.CreateCondBr(
302 Builder.CreateICmpNE(
303 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
304 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
305 CopyBegin, CopyEnd);
306 EmitBlock(CopyBegin);
307 }
308 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
309 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
310 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
311 SrcVD, AssignOp);
312 }
313 ++IRef;
314 ++ISrcRef;
315 ++IDestRef;
316 }
317 }
318 if (CopyEnd) {
319 // Exit out of copying procedure for non-master thread.
320 EmitBlock(CopyEnd, /*IsFinished=*/true);
321 return true;
322 }
323 return false;
324}
325
Alexey Bataev38e89532015-04-16 04:54:05 +0000326bool CodeGenFunction::EmitOMPLastprivateClauseInit(
327 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
328 auto LastprivateFilter = [](const OMPClause *C) -> bool {
329 return C->getClauseKind() == OMPC_lastprivate;
330 };
331 bool HasAtLeastOneLastprivate = false;
332 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
333 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
334 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
335 I; ++I) {
336 auto *C = cast<OMPLastprivateClause>(*I);
337 auto IRef = C->varlist_begin();
338 auto IDestRef = C->destination_exprs().begin();
339 for (auto *IInit : C->private_copies()) {
340 // Keep the address of the original variable for future update at the end
341 // of the loop.
342 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
343 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
344 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
345 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
346 DeclRefExpr DRE(
347 const_cast<VarDecl *>(OrigVD),
348 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
349 OrigVD) != nullptr,
350 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
351 return EmitLValue(&DRE).getAddress();
352 });
353 // Check if the variable is also a firstprivate: in this case IInit is
354 // not generated. Initialization of this variable will happen in codegen
355 // for 'firstprivate' clause.
356 if (!IInit)
357 continue;
358 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
359 bool IsRegistered =
360 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
361 // Emit private VarDecl with copy init.
362 EmitDecl(*VD);
363 return GetAddrOfLocalVar(VD);
364 });
365 assert(IsRegistered && "lastprivate var already registered as private");
366 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
367 }
368 ++IRef, ++IDestRef;
369 }
370 }
371 return HasAtLeastOneLastprivate;
372}
373
374void CodeGenFunction::EmitOMPLastprivateClauseFinal(
375 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
376 // Emit following code:
377 // if (<IsLastIterCond>) {
378 // orig_var1 = private_orig_var1;
379 // ...
380 // orig_varn = private_orig_varn;
381 // }
382 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
383 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
384 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
385 EmitBlock(ThenBB);
386 {
387 auto LastprivateFilter = [](const OMPClause *C) -> bool {
388 return C->getClauseKind() == OMPC_lastprivate;
389 };
390 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
391 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
392 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
393 I; ++I) {
394 auto *C = cast<OMPLastprivateClause>(*I);
395 auto IRef = C->varlist_begin();
396 auto ISrcRef = C->source_exprs().begin();
397 auto IDestRef = C->destination_exprs().begin();
398 for (auto *AssignOp : C->assignment_ops()) {
399 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
400 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
401 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
402 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
403 // Get the address of the original variable.
404 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
405 // Get the address of the private variable.
406 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
407 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
408 DestVD, SrcVD, AssignOp);
409 }
410 ++IRef;
411 ++ISrcRef;
412 ++IDestRef;
413 }
414 }
415 }
416 EmitBlock(DoneBB, /*IsFinished=*/true);
417}
418
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000419void CodeGenFunction::EmitOMPReductionClauseInit(
420 const OMPExecutableDirective &D,
421 CodeGenFunction::OMPPrivateScope &PrivateScope) {
422 auto ReductionFilter = [](const OMPClause *C) -> bool {
423 return C->getClauseKind() == OMPC_reduction;
424 };
425 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
426 ReductionFilter)> I(D.clauses(), ReductionFilter);
427 I; ++I) {
428 auto *C = cast<OMPReductionClause>(*I);
429 auto ILHS = C->lhs_exprs().begin();
430 auto IRHS = C->rhs_exprs().begin();
431 for (auto IRef : C->varlists()) {
432 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
433 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
434 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
435 // Store the address of the original variable associated with the LHS
436 // implicit variable.
437 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
438 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
439 CapturedStmtInfo->lookup(OrigVD) != nullptr,
440 IRef->getType(), VK_LValue, IRef->getExprLoc());
441 return EmitLValue(&DRE).getAddress();
442 });
443 // Emit reduction copy.
444 bool IsRegistered =
445 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
446 // Emit private VarDecl with reduction init.
447 EmitDecl(*PrivateVD);
448 return GetAddrOfLocalVar(PrivateVD);
449 });
450 assert(IsRegistered && "private var already registered as private");
451 // Silence the warning about unused variable.
452 (void)IsRegistered;
453 ++ILHS, ++IRHS;
454 }
455 }
456}
457
458void CodeGenFunction::EmitOMPReductionClauseFinal(
459 const OMPExecutableDirective &D) {
460 llvm::SmallVector<const Expr *, 8> LHSExprs;
461 llvm::SmallVector<const Expr *, 8> RHSExprs;
462 llvm::SmallVector<const Expr *, 8> ReductionOps;
463 auto ReductionFilter = [](const OMPClause *C) -> bool {
464 return C->getClauseKind() == OMPC_reduction;
465 };
466 bool HasAtLeastOneReduction = false;
467 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
468 ReductionFilter)> I(D.clauses(), ReductionFilter);
469 I; ++I) {
470 HasAtLeastOneReduction = true;
471 auto *C = cast<OMPReductionClause>(*I);
472 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
473 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
474 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
475 }
476 if (HasAtLeastOneReduction) {
477 // Emit nowait reduction if nowait clause is present or directive is a
478 // parallel directive (it always has implicit barrier).
479 CGM.getOpenMPRuntime().emitReduction(
480 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
481 D.getSingleClause(OMPC_nowait) ||
482 isOpenMPParallelDirective(D.getDirectiveKind()));
483 }
484}
485
Alexey Bataevb2059782014-10-13 08:23:51 +0000486/// \brief Emits code for OpenMP parallel directive in the parallel region.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000487static void emitOMPParallelCall(CodeGenFunction &CGF,
488 const OMPExecutableDirective &S,
Alexey Bataevb2059782014-10-13 08:23:51 +0000489 llvm::Value *OutlinedFn,
490 llvm::Value *CapturedStruct) {
491 if (auto C = S.getSingleClause(/*K*/ OMPC_num_threads)) {
492 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
493 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
494 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
495 /*IgnoreResultAssign*/ true);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000496 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Alexey Bataevb2059782014-10-13 08:23:51 +0000497 CGF, NumThreads, NumThreadsClause->getLocStart());
498 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000499 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
500 CapturedStruct);
Alexey Bataevb2059782014-10-13 08:23:51 +0000501}
502
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000503static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
504 const OMPExecutableDirective &S,
505 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000506 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000507 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
508 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
509 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000510 if (auto C = S.getSingleClause(/*K*/ OMPC_if)) {
511 auto Cond = cast<OMPIfClause>(C)->getCondition();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000512 EmitOMPIfClause(CGF, Cond, [&](bool ThenBlock) {
Alexey Bataevd74d0602014-10-13 06:02:40 +0000513 if (ThenBlock)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000514 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000515 else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000516 CGF.CGM.getOpenMPRuntime().emitSerialCall(CGF, S.getLocStart(),
517 OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000518 });
Alexey Bataevb2059782014-10-13 08:23:51 +0000519 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000520 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
521}
522
523void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
524 LexicalScope Scope(*this, S.getSourceRange());
525 // Emit parallel region as a standalone region.
526 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
527 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 bool Copyins = CGF.EmitOMPCopyinClause(S);
529 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
530 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000531 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000532 // initialization of firstprivate variables or propagation master's thread
533 // values of threadprivate variables to local instances of that variables
534 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000535 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
536 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000537 }
538 CGF.EmitOMPPrivateClause(S, PrivateScope);
539 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
540 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000541 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000542 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000543 // Emit implicit barrier at the end of the 'parallel' directive.
544 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
545 OMPD_unknown);
546 };
547 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000548}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000549
Alexander Musmand196ef22014-10-07 08:57:09 +0000550void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000551 bool SeparateIter) {
552 RunCleanupsScope BodyScope(*this);
553 // Update counters values on current iteration.
554 for (auto I : S.updates()) {
555 EmitIgnoredExpr(I);
556 }
Alexander Musman3276a272015-03-21 10:12:56 +0000557 // Update the linear variables.
558 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
559 for (auto U : C->updates()) {
560 EmitIgnoredExpr(U);
561 }
562 }
563
Alexander Musmana5f070a2014-10-01 06:03:56 +0000564 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000565 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000566 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
567 // Emit loop body.
568 EmitStmt(S.getBody());
569 // The end (updates/cleanups).
570 EmitBlock(Continue.getBlock());
571 BreakContinueStack.pop_back();
572 if (SeparateIter) {
573 // TODO: Update lastprivates if the SeparateIter flag is true.
574 // This will be implemented in a follow-up OMPLastprivateClause patch, but
575 // result should be still correct without it, as we do not make these
576 // variables private yet.
577 }
578}
579
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000580void CodeGenFunction::EmitOMPInnerLoop(
581 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
582 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000583 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
584 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000585 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000586 auto Cnt = getPGORegionCounter(&S);
587
588 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000589 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000590 EmitBlock(CondBlock);
591 LoopStack.push(CondBlock);
592
593 // If there are any cleanups between here and the loop-exit scope,
594 // create a block to stage a loop exit along.
595 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000596 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000597 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000598
Alexander Musmand196ef22014-10-07 08:57:09 +0000599 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000600
Alexey Bataev2df54a02015-03-12 08:53:29 +0000601 // Emit condition.
602 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, Cnt.getCount());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000603 if (ExitBlock != LoopExit.getBlock()) {
604 EmitBlock(ExitBlock);
605 EmitBranchThroughCleanup(LoopExit);
606 }
607
608 EmitBlock(LoopBody);
609 Cnt.beginRegion(Builder);
610
611 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000612 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000613 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
614
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000615 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000616
617 // Emit "IV = IV + 1" and a back-edge to the condition block.
618 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000619 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000620 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000621 BreakContinueStack.pop_back();
622 EmitBranch(CondBlock);
623 LoopStack.pop();
624 // Emit the fall-through block.
625 EmitBlock(LoopExit.getBlock());
626}
627
628void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
629 auto IC = S.counters().begin();
630 for (auto F : S.finals()) {
631 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
632 EmitIgnoredExpr(F);
633 }
634 ++IC;
635 }
Alexander Musman3276a272015-03-21 10:12:56 +0000636 // Emit the final values of the linear variables.
637 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
638 for (auto F : C->finals()) {
639 EmitIgnoredExpr(F);
640 }
641 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000642}
643
Alexander Musman09184fe2014-09-30 05:29:28 +0000644static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
645 const OMPAlignedClause &Clause) {
646 unsigned ClauseAlignment = 0;
647 if (auto AlignmentExpr = Clause.getAlignment()) {
648 auto AlignmentCI =
649 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
650 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
651 }
652 for (auto E : Clause.varlists()) {
653 unsigned Alignment = ClauseAlignment;
654 if (Alignment == 0) {
655 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000656 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000657 // alignments for SIMD instructions on the target platforms are assumed.
658 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
659 E->getType());
660 }
661 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
662 "alignment is not power of 2");
663 if (Alignment != 0) {
664 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
665 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
666 }
667 }
668}
669
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000670static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
671 CodeGenFunction::OMPPrivateScope &LoopScope,
672 ArrayRef<Expr *> Counters) {
673 for (auto *E : Counters) {
674 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
675 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
676 // Emit var without initialization.
677 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
678 CGF.EmitAutoVarCleanups(VarEmission);
679 return VarEmission.getAllocatedAddress();
680 });
681 assert(IsRegistered && "counter already registered as private");
682 // Silence the warning about unused variable.
683 (void)IsRegistered;
684 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000685}
686
Alexey Bataev62dbb972015-04-22 11:59:37 +0000687static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
688 const Expr *Cond, llvm::BasicBlock *TrueBlock,
689 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
690 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
691 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
692 const VarDecl *IVDecl =
693 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
694 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
695 // Emit var without initialization.
696 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
697 CGF.EmitAutoVarCleanups(VarEmission);
698 return VarEmission.getAllocatedAddress();
699 });
700 assert(IsRegistered && "counter already registered as private");
701 // Silence the warning about unused variable.
702 (void)IsRegistered;
703 (void)PreCondScope.Privatize();
704 // Initialize internal counter to 0 to calculate initial values of real
705 // counters.
706 LValue IV = CGF.EmitLValue(S.getIterationVariable());
707 CGF.EmitStoreOfScalar(
708 llvm::ConstantInt::getNullValue(
709 IV.getAddress()->getType()->getPointerElementType()),
710 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
711 // Get initial values of real counters.
712 for (auto I : S.updates()) {
713 CGF.EmitIgnoredExpr(I);
714 }
715 // Check that loop is executed at least one time.
716 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
717}
718
Alexander Musman3276a272015-03-21 10:12:56 +0000719static void
720EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
721 CodeGenFunction::OMPPrivateScope &PrivateScope) {
722 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
723 for (auto *E : Clause->varlists()) {
724 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
725 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
726 // Emit var without initialization.
727 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
728 CGF.EmitAutoVarCleanups(VarEmission);
729 return VarEmission.getAllocatedAddress();
730 });
731 assert(IsRegistered && "linear var already registered as private");
732 // Silence the warning about unused variable.
733 (void)IsRegistered;
734 }
735 }
736}
737
Alexander Musman515ad8c2014-05-22 08:54:05 +0000738void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000739 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
740 // Pragma 'simd' code depends on presence of 'lastprivate'.
741 // If present, we have to separate last iteration of the loop:
742 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000743 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000744 // for (IV in 0..LastIteration-1) BODY;
745 // BODY with updates of lastprivate vars;
746 // <Final counter/linear vars updates>;
747 // }
748 //
749 // otherwise (when there's no lastprivate):
750 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000751 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000752 // for (IV in 0..LastIteration) BODY;
753 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000754 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000755 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000756
Alexey Bataev62dbb972015-04-22 11:59:37 +0000757 // Emit: if (PreCond) - begin.
758 // If the condition constant folds and can be elided, avoid emitting the
759 // whole loop.
760 bool CondConstant;
761 llvm::BasicBlock *ContBlock = nullptr;
762 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
763 if (!CondConstant)
764 return;
765 } else {
766 RegionCounter Cnt = CGF.getPGORegionCounter(&S);
767 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
768 ContBlock = CGF.createBasicBlock("simd.if.end");
769 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
770 CGF.EmitBlock(ThenBlock);
771 Cnt.beginRegion(CGF.Builder);
772 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000773 // Walk clauses and process safelen/lastprivate.
774 bool SeparateIter = false;
775 CGF.LoopStack.setParallel();
776 CGF.LoopStack.setVectorizerEnable(true);
777 for (auto C : S.clauses()) {
778 switch (C->getClauseKind()) {
779 case OMPC_safelen: {
780 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
781 AggValueSlot::ignored(), true);
782 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
783 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
784 // In presence of finite 'safelen', it may be unsafe to mark all
785 // the memory instructions parallel, because loop-carried
786 // dependences of 'safelen' iterations are possible.
787 CGF.LoopStack.setParallel(false);
788 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000789 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000790 case OMPC_aligned:
791 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
792 break;
793 case OMPC_lastprivate:
794 SeparateIter = true;
795 break;
796 default:
797 // Not handled yet
798 ;
799 }
800 }
Alexander Musman3276a272015-03-21 10:12:56 +0000801
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000802 // Emit inits for the linear variables.
803 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
804 for (auto Init : C->inits()) {
805 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
806 CGF.EmitVarDecl(*D);
807 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000808 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000809
810 // Emit the loop iteration variable.
811 const Expr *IVExpr = S.getIterationVariable();
812 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
813 CGF.EmitVarDecl(*IVDecl);
814 CGF.EmitIgnoredExpr(S.getInit());
815
816 // Emit the iterations count variable.
817 // If it is not a variable, Sema decided to calculate iterations count on
818 // each
819 // iteration (e.g., it is foldable into a constant).
820 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
821 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
822 // Emit calculation of the iterations count.
823 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000824 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000825
826 // Emit the linear steps for the linear clauses.
827 // If a step is not constant, it is pre-calculated before the loop.
828 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
829 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
830 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
831 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
832 // Emit calculation of the linear step.
833 CGF.EmitIgnoredExpr(CS);
834 }
835 }
836
Alexey Bataev62dbb972015-04-22 11:59:37 +0000837 {
838 OMPPrivateScope LoopScope(CGF);
839 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
840 EmitPrivateLinearVars(CGF, S, LoopScope);
841 CGF.EmitOMPPrivateClause(S, LoopScope);
842 (void)LoopScope.Privatize();
843 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
844 S.getCond(SeparateIter), S.getInc(),
845 [&S](CodeGenFunction &CGF) {
846 CGF.EmitOMPLoopBody(S);
847 CGF.EmitStopPoint(&S);
848 },
849 [](CodeGenFunction &) {});
850 if (SeparateIter) {
851 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000852 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000853 }
854 CGF.EmitOMPSimdFinal(S);
855 // Emit: if (PreCond) - end.
856 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000857 CGF.EmitBranch(ContBlock);
858 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000859 }
860 };
861 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000862}
863
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000864void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
865 const OMPLoopDirective &S,
866 OMPPrivateScope &LoopScope,
867 llvm::Value *LB, llvm::Value *UB,
868 llvm::Value *ST, llvm::Value *IL,
869 llvm::Value *Chunk) {
870 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000871
872 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
873 const bool Dynamic = RT.isDynamic(ScheduleKind);
874
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000875 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
876 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000877
878 // Emit outer loop.
879 //
880 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000881 // When schedule(dynamic,chunk_size) is specified, the iterations are
882 // distributed to threads in the team in chunks as the threads request them.
883 // Each thread executes a chunk of iterations, then requests another chunk,
884 // until no chunks remain to be distributed. Each chunk contains chunk_size
885 // iterations, except for the last chunk to be distributed, which may have
886 // fewer iterations. When no chunk_size is specified, it defaults to 1.
887 //
888 // When schedule(guided,chunk_size) is specified, the iterations are assigned
889 // to threads in the team in chunks as the executing threads request them.
890 // Each thread executes a chunk of iterations, then requests another chunk,
891 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
892 // each chunk is proportional to the number of unassigned iterations divided
893 // by the number of threads in the team, decreasing to 1. For a chunk_size
894 // with value k (greater than 1), the size of each chunk is determined in the
895 // same way, with the restriction that the chunks do not contain fewer than k
896 // iterations (except for the last chunk to be assigned, which may have fewer
897 // than k iterations).
898 //
899 // When schedule(auto) is specified, the decision regarding scheduling is
900 // delegated to the compiler and/or runtime system. The programmer gives the
901 // implementation the freedom to choose any possible mapping of iterations to
902 // threads in the team.
903 //
904 // When schedule(runtime) is specified, the decision regarding scheduling is
905 // deferred until run time, and the schedule and chunk size are taken from the
906 // run-sched-var ICV. If the ICV is set to auto, the schedule is
907 // implementation defined
908 //
909 // while(__kmpc_dispatch_next(&LB, &UB)) {
910 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000911 // while (idx <= UB) { BODY; ++idx;
912 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
913 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000914 // }
915 //
916 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000917 // When schedule(static, chunk_size) is specified, iterations are divided into
918 // chunks of size chunk_size, and the chunks are assigned to the threads in
919 // the team in a round-robin fashion in the order of the thread number.
920 //
921 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
922 // while (idx <= UB) { BODY; ++idx; } // inner loop
923 // LB = LB + ST;
924 // UB = UB + ST;
925 // }
926 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000927
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000928 const Expr *IVExpr = S.getIterationVariable();
929 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
930 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
931
Alexander Musman92bdaab2015-03-12 13:37:50 +0000932 RT.emitForInit(
933 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
934 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
935 Chunk);
936
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000937 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
938
939 // Start the loop with a block that tests the condition.
940 auto CondBlock = createBasicBlock("omp.dispatch.cond");
941 EmitBlock(CondBlock);
942 LoopStack.push(CondBlock);
943
944 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000945 if (!Dynamic) {
946 // UB = min(UB, GlobalUB)
947 EmitIgnoredExpr(S.getEnsureUpperBound());
948 // IV = LB
949 EmitIgnoredExpr(S.getInit());
950 // IV < UB
951 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
952 } else {
953 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
954 IL, LB, UB, ST);
955 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000956
957 // If there are any cleanups between here and the loop-exit scope,
958 // create a block to stage a loop exit along.
959 auto ExitBlock = LoopExit.getBlock();
960 if (LoopScope.requiresCleanups())
961 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
962
963 auto LoopBody = createBasicBlock("omp.dispatch.body");
964 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
965 if (ExitBlock != LoopExit.getBlock()) {
966 EmitBlock(ExitBlock);
967 EmitBranchThroughCleanup(LoopExit);
968 }
969 EmitBlock(LoopBody);
970
Alexander Musman92bdaab2015-03-12 13:37:50 +0000971 // Emit "IV = LB" (in case of static schedule, we have already calculated new
972 // LB for loop condition and emitted it above).
973 if (Dynamic)
974 EmitIgnoredExpr(S.getInit());
975
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000976 // Create a block for the increment.
977 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
978 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
979
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000980 bool DynamicWithOrderedClause =
981 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
982 SourceLocation Loc = S.getLocStart();
983 EmitOMPInnerLoop(
984 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
985 S.getInc(),
986 [&S](CodeGenFunction &CGF) {
987 CGF.EmitOMPLoopBody(S);
988 CGF.EmitStopPoint(&S);
989 },
990 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
991 if (DynamicWithOrderedClause) {
992 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
993 CGF, Loc, IVSize, IVSigned);
994 }
995 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000996
997 EmitBlock(Continue.getBlock());
998 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000999 if (!Dynamic) {
1000 // Emit "LB = LB + Stride", "UB = UB + Stride".
1001 EmitIgnoredExpr(S.getNextLowerBound());
1002 EmitIgnoredExpr(S.getNextUpperBound());
1003 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001004
1005 EmitBranch(CondBlock);
1006 LoopStack.pop();
1007 // Emit the fall-through block.
1008 EmitBlock(LoopExit.getBlock());
1009
1010 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001011 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001012 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001013}
1014
Alexander Musmanc6388682014-12-15 07:07:06 +00001015/// \brief Emit a helper variable and return corresponding lvalue.
1016static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1017 const DeclRefExpr *Helper) {
1018 auto VDecl = cast<VarDecl>(Helper->getDecl());
1019 CGF.EmitVarDecl(*VDecl);
1020 return CGF.EmitLValue(Helper);
1021}
1022
Alexey Bataev38e89532015-04-16 04:54:05 +00001023bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001024 // Emit the loop iteration variable.
1025 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1026 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1027 EmitVarDecl(*IVDecl);
1028
1029 // Emit the iterations count variable.
1030 // If it is not a variable, Sema decided to calculate iterations count on each
1031 // iteration (e.g., it is foldable into a constant).
1032 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1033 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1034 // Emit calculation of the iterations count.
1035 EmitIgnoredExpr(S.getCalcLastIteration());
1036 }
1037
1038 auto &RT = CGM.getOpenMPRuntime();
1039
Alexey Bataev38e89532015-04-16 04:54:05 +00001040 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001041 // Check pre-condition.
1042 {
1043 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001044 // If the condition constant folds and can be elided, avoid emitting the
1045 // whole loop.
1046 bool CondConstant;
1047 llvm::BasicBlock *ContBlock = nullptr;
1048 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1049 if (!CondConstant)
1050 return false;
1051 } else {
1052 RegionCounter Cnt = getPGORegionCounter(&S);
1053 auto *ThenBlock = createBasicBlock("omp.precond.then");
1054 ContBlock = createBasicBlock("omp.precond.end");
1055 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
1056 Cnt.getCount());
1057 EmitBlock(ThenBlock);
1058 Cnt.beginRegion(Builder);
1059 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001060 // Emit 'then' code.
1061 {
1062 // Emit helper vars inits.
1063 LValue LB =
1064 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1065 LValue UB =
1066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1067 LValue ST =
1068 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1069 LValue IL =
1070 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1071
1072 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001073 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1074 // Emit implicit barrier to synchronize threads and avoid data races on
1075 // initialization of firstprivate variables.
1076 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1077 OMPD_unknown);
1078 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001079 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001080 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001081 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001082 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001083
1084 // Detect the loop schedule kind and chunk.
1085 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1086 llvm::Value *Chunk = nullptr;
1087 if (auto C = cast_or_null<OMPScheduleClause>(
1088 S.getSingleClause(OMPC_schedule))) {
1089 ScheduleKind = C->getScheduleKind();
1090 if (auto Ch = C->getChunkSize()) {
1091 Chunk = EmitScalarExpr(Ch);
1092 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1093 S.getIterationVariable()->getType());
1094 }
1095 }
1096 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1097 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1098 if (RT.isStaticNonchunked(ScheduleKind,
1099 /* Chunked */ Chunk != nullptr)) {
1100 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1101 // When no chunk_size is specified, the iteration space is divided into
1102 // chunks that are approximately equal in size, and at most one chunk is
1103 // distributed to each thread. Note that the size of the chunks is
1104 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001105 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1106 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1107 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001108 // UB = min(UB, GlobalUB);
1109 EmitIgnoredExpr(S.getEnsureUpperBound());
1110 // IV = LB;
1111 EmitIgnoredExpr(S.getInit());
1112 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001113 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1114 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001115 [&S](CodeGenFunction &CGF) {
1116 CGF.EmitOMPLoopBody(S);
1117 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001118 },
1119 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001120 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001121 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001122 } else {
1123 // Emit the outer loop, which requests its work chunk [LB..UB] from
1124 // runtime and runs the inner loop to process it.
1125 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1126 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1127 Chunk);
1128 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001129 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1130 if (HasLastprivateClause)
1131 EmitOMPLastprivateClauseFinal(
1132 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001133 }
1134 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001135 if (ContBlock) {
1136 EmitBranch(ContBlock);
1137 EmitBlock(ContBlock, true);
1138 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001139 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001140 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001141}
1142
1143void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001144 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001145 bool HasLastprivates = false;
1146 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1147 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1148 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001149 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001150
1151 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001152 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001153 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1154 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001155}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001156
Alexander Musmanf82886e2014-09-18 05:12:34 +00001157void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1158 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1159}
1160
Alexey Bataev2df54a02015-03-12 08:53:29 +00001161static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1162 const Twine &Name,
1163 llvm::Value *Init = nullptr) {
1164 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1165 if (Init)
1166 CGF.EmitScalarInit(Init, LVal);
1167 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001168}
1169
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001170static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1171 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001172 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1173 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1174 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
1176 auto &C = CGF.CGM.getContext();
1177 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1178 // Emit helper vars inits.
1179 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1180 CGF.Builder.getInt32(0));
1181 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1182 LValue UB =
1183 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1184 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1185 CGF.Builder.getInt32(1));
1186 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1187 CGF.Builder.getInt32(0));
1188 // Loop counter.
1189 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1190 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001191 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001192 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001193 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001194 // Generate condition for loop.
1195 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1196 OK_Ordinary, S.getLocStart(),
1197 /*fpContractable=*/false);
1198 // Increment for loop counter.
1199 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1200 OK_Ordinary, S.getLocStart());
1201 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1202 // Iterate through all sections and emit a switch construct:
1203 // switch (IV) {
1204 // case 0:
1205 // <SectionStmt[0]>;
1206 // break;
1207 // ...
1208 // case <NumSection> - 1:
1209 // <SectionStmt[<NumSection> - 1]>;
1210 // break;
1211 // }
1212 // .omp.sections.exit:
1213 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1214 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1215 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1216 CS->size());
1217 unsigned CaseNumber = 0;
1218 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1219 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1220 CGF.EmitBlock(CaseBB);
1221 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1222 CGF.EmitStmt(*C);
1223 CGF.EmitBranch(ExitBB);
1224 }
1225 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1226 };
1227 // Emit static non-chunked loop.
1228 CGF.CGM.getOpenMPRuntime().emitForInit(
1229 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1230 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1231 ST.getAddress());
1232 // UB = min(UB, GlobalUB);
1233 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1234 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1235 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1236 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1237 // IV = LB;
1238 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1239 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001240 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1241 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001242 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001243 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001244 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001246 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1247 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001248 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001249 // If only one section is found - no need to generate loop, emit as a single
1250 // region.
1251 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
1252 CGF.EmitStmt(Stmt);
1253 CGF.EnsureInsertPoint();
1254 };
1255 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1256 llvm::None, llvm::None,
1257 llvm::None, llvm::None);
1258 return OMPD_single;
1259}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001260
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001261void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1262 LexicalScope Scope(*this, S.getSourceRange());
1263 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001264 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001265 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001266 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001267 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001268}
1269
1270void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001271 LexicalScope Scope(*this, S.getSourceRange());
1272 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1273 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1274 CGF.EnsureInsertPoint();
1275 };
1276 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001277}
1278
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001279void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001280 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001281 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001282 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001283 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001284 // Check if there are any 'copyprivate' clauses associated with this
1285 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001286 // construct.
1287 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1288 return C->getClauseKind() == OMPC_copyprivate;
1289 };
1290 // Build a list of copyprivate variables along with helper expressions
1291 // (<source>, <destination>, <destination>=<source> expressions)
1292 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1293 CopyprivateFilter)> CopyprivateIter;
1294 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1295 auto *C = cast<OMPCopyprivateClause>(*I);
1296 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001297 DestExprs.append(C->destination_exprs().begin(),
1298 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001299 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001300 AssignmentOps.append(C->assignment_ops().begin(),
1301 C->assignment_ops().end());
1302 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001303 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001304 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001305 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1306 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1307 CGF.EnsureInsertPoint();
1308 };
1309 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001310 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001311 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001312 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001313 if (!S.getSingleClause(OMPC_nowait)) {
1314 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1315 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001316}
1317
Alexey Bataev8d690652014-12-04 07:23:53 +00001318void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001319 LexicalScope Scope(*this, S.getSourceRange());
1320 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1321 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1322 CGF.EnsureInsertPoint();
1323 };
1324 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001325}
1326
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001327void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001328 LexicalScope Scope(*this, S.getSourceRange());
1329 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1330 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1331 CGF.EnsureInsertPoint();
1332 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001333 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001334 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001335}
1336
Alexey Bataev671605e2015-04-13 05:28:11 +00001337void CodeGenFunction::EmitOMPParallelForDirective(
1338 const OMPParallelForDirective &S) {
1339 // Emit directive as a combined directive that consists of two implicit
1340 // directives: 'parallel' with 'for' directive.
1341 LexicalScope Scope(*this, S.getSourceRange());
1342 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1343 CGF.EmitOMPWorksharingLoop(S);
1344 // Emit implicit barrier at the end of parallel region, but this barrier
1345 // is at the end of 'for' directive, so emit it as the implicit barrier for
1346 // this 'for' directive.
1347 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1348 OMPD_parallel);
1349 };
1350 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001351}
1352
Alexander Musmane4e893b2014-09-23 09:33:00 +00001353void CodeGenFunction::EmitOMPParallelForSimdDirective(
1354 const OMPParallelForSimdDirective &) {
1355 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1356}
1357
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001358void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001359 const OMPParallelSectionsDirective &S) {
1360 // Emit directive as a combined directive that consists of two implicit
1361 // directives: 'parallel' with 'sections' directive.
1362 LexicalScope Scope(*this, S.getSourceRange());
1363 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1364 (void)emitSections(CGF, S);
1365 // Emit implicit barrier at the end of parallel region.
1366 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1367 OMPD_parallel);
1368 };
1369 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001370}
1371
Alexey Bataev62b63b12015-03-10 07:28:44 +00001372void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1373 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001374 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001375 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1376 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1377 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001378 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001379 // The first function argument for tasks is a thread id, the second one is a
1380 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001381 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1382 if (*PartId) {
1383 // TODO: emit code for untied tasks.
1384 }
1385 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1386 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001387 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001388 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001389 // Check if we should emit tied or untied task.
1390 bool Tied = !S.getSingleClause(OMPC_untied);
1391 // Check if the task is final
1392 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1393 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1394 // If the condition constant folds and can be elided, try to avoid emitting
1395 // the condition and the dead arm of the if/else.
1396 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1397 bool CondConstant;
1398 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1399 Final.setInt(CondConstant);
1400 else
1401 Final.setPointer(EvaluateExprAsBool(Cond));
1402 } else {
1403 // By default the task is not final.
1404 Final.setInt(/*IntVal=*/false);
1405 }
1406 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
1407 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
1408 OutlinedFn, SharedsTy, CapturedStruct);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001409}
1410
Alexey Bataev9f797f32015-02-05 05:57:51 +00001411void CodeGenFunction::EmitOMPTaskyieldDirective(
1412 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001413 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001414}
1415
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001416void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001417 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001418}
1419
Alexey Bataev2df347a2014-07-18 10:17:07 +00001420void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1421 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1422}
1423
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001424void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001425 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1426 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1427 auto FlushClause = cast<OMPFlushClause>(C);
1428 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1429 FlushClause->varlist_end());
1430 }
1431 return llvm::None;
1432 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001433}
1434
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001435void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1436 LexicalScope Scope(*this, S.getSourceRange());
1437 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1438 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1439 CGF.EnsureInsertPoint();
1440 };
1441 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001442}
1443
Alexey Bataevb57056f2015-01-22 06:17:56 +00001444static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1445 QualType SrcType, QualType DestType) {
1446 assert(CGF.hasScalarEvaluationKind(DestType) &&
1447 "DestType must have scalar evaluation kind.");
1448 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1449 return Val.isScalar()
1450 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1451 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1452 DestType);
1453}
1454
1455static CodeGenFunction::ComplexPairTy
1456convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1457 QualType DestType) {
1458 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1459 "DestType must have complex evaluation kind.");
1460 CodeGenFunction::ComplexPairTy ComplexVal;
1461 if (Val.isScalar()) {
1462 // Convert the input element to the element type of the complex.
1463 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1464 auto ScalarVal =
1465 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1466 ComplexVal = CodeGenFunction::ComplexPairTy(
1467 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1468 } else {
1469 assert(Val.isComplex() && "Must be a scalar or complex.");
1470 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1471 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1472 ComplexVal.first = CGF.EmitScalarConversion(
1473 Val.getComplexVal().first, SrcElementType, DestElementType);
1474 ComplexVal.second = CGF.EmitScalarConversion(
1475 Val.getComplexVal().second, SrcElementType, DestElementType);
1476 }
1477 return ComplexVal;
1478}
1479
1480static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1481 const Expr *X, const Expr *V,
1482 SourceLocation Loc) {
1483 // v = x;
1484 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1485 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1486 LValue XLValue = CGF.EmitLValue(X);
1487 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001488 RValue Res = XLValue.isGlobalReg()
1489 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1490 : CGF.EmitAtomicLoad(XLValue, Loc,
1491 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001492 : llvm::Monotonic,
1493 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001494 // OpenMP, 2.12.6, atomic Construct
1495 // Any atomic construct with a seq_cst clause forces the atomically
1496 // performed operation to include an implicit flush operation without a
1497 // list.
1498 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001499 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001500 switch (CGF.getEvaluationKind(V->getType())) {
1501 case TEK_Scalar:
1502 CGF.EmitStoreOfScalar(
1503 convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
1504 break;
1505 case TEK_Complex:
1506 CGF.EmitStoreOfComplex(
1507 convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
1508 /*isInit=*/false);
1509 break;
1510 case TEK_Aggregate:
1511 llvm_unreachable("Must be a scalar or complex.");
1512 }
1513}
1514
Alexey Bataevb8329262015-02-27 06:33:30 +00001515static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1516 const Expr *X, const Expr *E,
1517 SourceLocation Loc) {
1518 // x = expr;
1519 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
1520 LValue XLValue = CGF.EmitLValue(X);
1521 RValue ExprRValue = CGF.EmitAnyExpr(E);
1522 if (XLValue.isGlobalReg())
1523 CGF.EmitStoreThroughGlobalRegLValue(ExprRValue, XLValue);
1524 else
1525 CGF.EmitAtomicStore(ExprRValue, XLValue,
1526 IsSeqCst ? llvm::SequentiallyConsistent
1527 : llvm::Monotonic,
1528 XLValue.isVolatile(), /*IsInit=*/false);
1529 // OpenMP, 2.12.6, atomic Construct
1530 // Any atomic construct with a seq_cst clause forces the atomically
1531 // performed operation to include an implicit flush operation without a
1532 // list.
1533 if (IsSeqCst)
1534 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1535}
1536
Benjamin Kramer5df7c1a2015-04-18 10:00:10 +00001537static bool emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update,
1538 BinaryOperatorKind BO, llvm::AtomicOrdering AO,
1539 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001540 auto &Context = CGF.CGM.getContext();
1541 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001542 // expression is simple and atomic is allowed for the given type for the
1543 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001544 if (BO == BO_Comma || !Update.isScalar() ||
1545 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1546 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1547 (Update.getScalarVal()->getType() !=
1548 X.getAddress()->getType()->getPointerElementType())) ||
1549 !Context.getTargetInfo().hasBuiltinAtomic(
1550 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
1551 return false;
1552
1553 llvm::AtomicRMWInst::BinOp RMWOp;
1554 switch (BO) {
1555 case BO_Add:
1556 RMWOp = llvm::AtomicRMWInst::Add;
1557 break;
1558 case BO_Sub:
1559 if (!IsXLHSInRHSPart)
1560 return false;
1561 RMWOp = llvm::AtomicRMWInst::Sub;
1562 break;
1563 case BO_And:
1564 RMWOp = llvm::AtomicRMWInst::And;
1565 break;
1566 case BO_Or:
1567 RMWOp = llvm::AtomicRMWInst::Or;
1568 break;
1569 case BO_Xor:
1570 RMWOp = llvm::AtomicRMWInst::Xor;
1571 break;
1572 case BO_LT:
1573 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1574 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1575 : llvm::AtomicRMWInst::Max)
1576 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1577 : llvm::AtomicRMWInst::UMax);
1578 break;
1579 case BO_GT:
1580 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1581 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1582 : llvm::AtomicRMWInst::Min)
1583 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1584 : llvm::AtomicRMWInst::UMin);
1585 break;
1586 case BO_Mul:
1587 case BO_Div:
1588 case BO_Rem:
1589 case BO_Shl:
1590 case BO_Shr:
1591 case BO_LAnd:
1592 case BO_LOr:
1593 return false;
1594 case BO_PtrMemD:
1595 case BO_PtrMemI:
1596 case BO_LE:
1597 case BO_GE:
1598 case BO_EQ:
1599 case BO_NE:
1600 case BO_Assign:
1601 case BO_AddAssign:
1602 case BO_SubAssign:
1603 case BO_AndAssign:
1604 case BO_OrAssign:
1605 case BO_XorAssign:
1606 case BO_MulAssign:
1607 case BO_DivAssign:
1608 case BO_RemAssign:
1609 case BO_ShlAssign:
1610 case BO_ShrAssign:
1611 case BO_Comma:
1612 llvm_unreachable("Unsupported atomic update operation");
1613 }
1614 auto *UpdateVal = Update.getScalarVal();
1615 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1616 UpdateVal = CGF.Builder.CreateIntCast(
1617 IC, X.getAddress()->getType()->getPointerElementType(),
1618 X.getType()->hasSignedIntegerRepresentation());
1619 }
1620 CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1621 return true;
1622}
1623
1624void CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
1625 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1626 llvm::AtomicOrdering AO, SourceLocation Loc,
1627 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1628 // Update expressions are allowed to have the following forms:
1629 // x binop= expr; -> xrval + expr;
1630 // x++, ++x -> xrval + 1;
1631 // x--, --x -> xrval - 1;
1632 // x = x binop expr; -> xrval binop expr
1633 // x = expr Op x; - > expr binop xrval;
1634 if (!emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart)) {
1635 if (X.isGlobalReg()) {
1636 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1637 // 'xrval'.
1638 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1639 } else {
1640 // Perform compare-and-swap procedure.
1641 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001642 }
1643 }
Alexey Bataevb4505a72015-03-30 05:20:59 +00001644}
1645
1646static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1647 const Expr *X, const Expr *E,
1648 const Expr *UE, bool IsXLHSInRHSPart,
1649 SourceLocation Loc) {
1650 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1651 "Update expr in 'atomic update' must be a binary operator.");
1652 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1653 // Update expressions are allowed to have the following forms:
1654 // x binop= expr; -> xrval + expr;
1655 // x++, ++x -> xrval + 1;
1656 // x--, --x -> xrval - 1;
1657 // x = x binop expr; -> xrval binop expr
1658 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001659 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001660 LValue XLValue = CGF.EmitLValue(X);
1661 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001662 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001663 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1664 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1665 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1666 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1667 auto Gen =
1668 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1669 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1670 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1671 return CGF.EmitAnyExpr(UE);
1672 };
1673 CGF.EmitOMPAtomicSimpleUpdateExpr(XLValue, ExprRValue, BOUE->getOpcode(),
1674 IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001675 // OpenMP, 2.12.6, atomic Construct
1676 // Any atomic construct with a seq_cst clause forces the atomically
1677 // performed operation to include an implicit flush operation without a
1678 // list.
1679 if (IsSeqCst)
1680 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1681}
1682
Alexey Bataevb57056f2015-01-22 06:17:56 +00001683static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
1684 bool IsSeqCst, const Expr *X, const Expr *V,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001685 const Expr *E, const Expr *UE,
1686 bool IsXLHSInRHSPart, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001687 switch (Kind) {
1688 case OMPC_read:
1689 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1690 break;
1691 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001692 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1693 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001694 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001695 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001696 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1697 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001698 case OMPC_capture:
1699 llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
1700 case OMPC_if:
1701 case OMPC_final:
1702 case OMPC_num_threads:
1703 case OMPC_private:
1704 case OMPC_firstprivate:
1705 case OMPC_lastprivate:
1706 case OMPC_reduction:
1707 case OMPC_safelen:
1708 case OMPC_collapse:
1709 case OMPC_default:
1710 case OMPC_seq_cst:
1711 case OMPC_shared:
1712 case OMPC_linear:
1713 case OMPC_aligned:
1714 case OMPC_copyin:
1715 case OMPC_copyprivate:
1716 case OMPC_flush:
1717 case OMPC_proc_bind:
1718 case OMPC_schedule:
1719 case OMPC_ordered:
1720 case OMPC_nowait:
1721 case OMPC_untied:
1722 case OMPC_threadprivate:
1723 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001724 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1725 }
1726}
1727
1728void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1729 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1730 OpenMPClauseKind Kind = OMPC_unknown;
1731 for (auto *C : S.clauses()) {
1732 // Find first clause (skip seq_cst clause, if it is first).
1733 if (C->getClauseKind() != OMPC_seq_cst) {
1734 Kind = C->getClauseKind();
1735 break;
1736 }
1737 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001738
1739 const auto *CS =
1740 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
1741 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
1742 enterFullExpression(EWC);
Alexey Bataev10fec572015-03-11 04:48:56 +00001743
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001744 LexicalScope Scope(*this, S.getSourceRange());
1745 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
1746 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
1747 S.getUpdateExpr(), S.isXLHSInRHSPart(), S.getLocStart());
1748 };
1749 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001750}
1751
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001752void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1753 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1754}
1755
Alexey Bataev13314bf2014-10-09 04:18:56 +00001756void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1757 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1758}
1759