blob: 06860f8e892bb35f97a3810456f7082ce9075daa [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
20using namespace clang;
21using namespace CodeGen;
22
23//===----------------------------------------------------------------------===//
24// OpenMP Directive Emission
25//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +000026void CodeGenFunction::EmitOMPAggregateAssign(
27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) {
29 // Perform element-by-element initialization.
30 QualType ElementTy;
31 auto SrcBegin = SrcAddr;
32 auto DestBegin = DestAddr;
33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
35 // Cast from pointer to array type to pointer to single element.
36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin,
37 DestBegin->getType());
38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
39 // The basic structure here is a while-do loop.
40 auto BodyBB = createBasicBlock("omp.arraycpy.body");
41 auto DoneBB = createBasicBlock("omp.arraycpy.done");
42 auto IsEmpty =
43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000045
Alexey Bataev420d45b2015-04-14 05:11:24 +000046 // Enter the loop body, making that address the current address.
47 auto EntryBB = Builder.GetInsertBlock();
48 EmitBlock(BodyBB);
49 auto SrcElementCurrent =
50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB);
52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2,
53 "omp.arraycpy.destElementPast");
54 DestElementCurrent->addIncoming(DestBegin, EntryBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000055
Alexey Bataev420d45b2015-04-14 05:11:24 +000056 // Emit copy.
57 CopyGen(DestElementCurrent, SrcElementCurrent);
58
59 // Shift the address forward by one element.
60 auto DestElementNext = Builder.CreateConstGEP1_32(
61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element");
62 auto SrcElementNext = Builder.CreateConstGEP1_32(
63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element");
64 // Check whether we've reached the end.
65 auto Done =
66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
67 Builder.CreateCondBr(Done, DoneBB, BodyBB);
68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock());
69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock());
70
71 // Done.
72 EmitBlock(DoneBB, /*IsFinished=*/true);
73}
74
75void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF,
76 QualType OriginalType, llvm::Value *DestAddr,
77 llvm::Value *SrcAddr, const VarDecl *DestVD,
78 const VarDecl *SrcVD, const Expr *Copy) {
79 if (OriginalType->isArrayType()) {
80 auto *BO = dyn_cast<BinaryOperator>(Copy);
81 if (BO && BO->getOpcode() == BO_Assign) {
82 // Perform simple memcpy for simple copying.
83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
84 } else {
85 // For arrays with complex element types perform element by element
86 // copying.
87 CGF.EmitOMPAggregateAssign(
88 DestAddr, SrcAddr, OriginalType,
89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement,
90 llvm::Value *SrcElement) {
91 // Working with the single array element, so have to remap
92 // destination and source variables to corresponding array
93 // elements.
94 CodeGenFunction::OMPPrivateScope Remap(CGF);
95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{
96 return DestElement;
97 });
98 Remap.addPrivate(
99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; });
100 (void)Remap.Privatize();
101 CGF.EmitIgnoredExpr(Copy);
102 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000103 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000104 } else {
105 // Remap pseudo source variable to private copy.
106 CodeGenFunction::OMPPrivateScope Remap(CGF);
107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; });
108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; });
109 (void)Remap.Privatize();
110 // Emit copying of the whole variable.
111 CGF.EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000112 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000113}
114
Alexey Bataev69c62a92015-04-15 04:52:20 +0000115bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
116 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000119 auto *C = cast<OMPFirstprivateClause>(*I);
120 auto IRef = C->varlist_begin();
121 auto InitsRef = C->inits().begin();
122 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000124 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
125 EmittedAsFirstprivate.insert(OrigVD);
126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
128 bool IsRegistered;
129 DeclRefExpr DRE(
130 const_cast<VarDecl *>(OrigVD),
131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
132 OrigVD) != nullptr,
133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
134 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000135 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000136 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000137 // Emit VarDecl with copy init for arrays.
138 // Get the address of the original variable captured in current
139 // captured region.
140 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
141 auto Emission = EmitAutoVarAlloca(*VD);
142 auto *Init = VD->getInit();
143 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
144 // Perform simple memcpy.
145 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000146 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000147 } else {
148 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000149 Emission.getAllocatedAddress(), OriginalAddr, Type,
Alexey Bataev69c62a92015-04-15 04:52:20 +0000150 [this, VDInit, Init](llvm::Value *DestElement,
151 llvm::Value *SrcElement) {
152 // Clean up any temporaries needed by the initialization.
153 RunCleanupsScope InitScope(*this);
154 // Emit initialization for single element.
155 LocalDeclMap[VDInit] = SrcElement;
156 EmitAnyExprToMem(Init, DestElement,
157 Init->getType().getQualifiers(),
158 /*IsInitializer*/ false);
159 LocalDeclMap.erase(VDInit);
160 });
161 }
162 EmitAutoVarCleanups(Emission);
163 return Emission.getAllocatedAddress();
164 });
165 } else {
166 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
167 // Emit private VarDecl with copy init.
168 // Remap temp VDInit variable to the address of the original
169 // variable
170 // (for proper handling of captured global variables).
171 LocalDeclMap[VDInit] = OriginalAddr;
172 EmitDecl(*VD);
173 LocalDeclMap.erase(VDInit);
174 return GetAddrOfLocalVar(VD);
175 });
176 }
177 assert(IsRegistered &&
178 "firstprivate var already registered as private");
179 // Silence the warning about unused variable.
180 (void)IsRegistered;
181 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000182 ++IRef, ++InitsRef;
183 }
184 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000185 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000186}
187
Alexey Bataev03b340a2014-10-21 03:16:40 +0000188void CodeGenFunction::EmitOMPPrivateClause(
189 const OMPExecutableDirective &D,
190 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000191 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000192 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193 auto *C = cast<OMPPrivateClause>(*I);
194 auto IRef = C->varlist_begin();
195 for (auto IInit : C->private_copies()) {
196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000197 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
198 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
199 bool IsRegistered =
200 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
201 // Emit private VarDecl with copy init.
202 EmitDecl(*VD);
203 return GetAddrOfLocalVar(VD);
204 });
205 assert(IsRegistered && "private var already registered as private");
206 // Silence the warning about unused variable.
207 (void)IsRegistered;
208 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000209 ++IRef;
210 }
211 }
212}
213
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000214bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
215 // threadprivate_var1 = master_threadprivate_var1;
216 // operator=(threadprivate_var2, master_threadprivate_var2);
217 // ...
218 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000219 llvm::DenseSet<const VarDecl *> CopiedVars;
220 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000221 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 auto *C = cast<OMPCopyinClause>(*I);
223 auto IRef = C->varlist_begin();
224 auto ISrcRef = C->source_exprs().begin();
225 auto IDestRef = C->destination_exprs().begin();
226 for (auto *AssignOp : C->assignment_ops()) {
227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000228 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000229 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
230 // Get the address of the master variable.
231 auto *MasterAddr = VD->isStaticLocal()
232 ? CGM.getStaticLocalDeclAddress(VD)
233 : CGM.GetAddrOfGlobal(VD);
234 // Get the address of the threadprivate variable.
235 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
236 if (CopiedVars.size() == 1) {
237 // At first check if current thread is a master thread. If it is, no
238 // need to copy data.
239 CopyBegin = createBasicBlock("copyin.not.master");
240 CopyEnd = createBasicBlock("copyin.not.master.end");
241 Builder.CreateCondBr(
242 Builder.CreateICmpNE(
243 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
244 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
245 CopyBegin, CopyEnd);
246 EmitBlock(CopyBegin);
247 }
248 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
249 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000250 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD,
251 AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000252 }
253 ++IRef;
254 ++ISrcRef;
255 ++IDestRef;
256 }
257 }
258 if (CopyEnd) {
259 // Exit out of copying procedure for non-master thread.
260 EmitBlock(CopyEnd, /*IsFinished=*/true);
261 return true;
262 }
263 return false;
264}
265
Alexey Bataev38e89532015-04-16 04:54:05 +0000266bool CodeGenFunction::EmitOMPLastprivateClauseInit(
267 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000268 bool HasAtLeastOneLastprivate = false;
269 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000270 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000271 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000272 auto *C = cast<OMPLastprivateClause>(*I);
273 auto IRef = C->varlist_begin();
274 auto IDestRef = C->destination_exprs().begin();
275 for (auto *IInit : C->private_copies()) {
276 // Keep the address of the original variable for future update at the end
277 // of the loop.
278 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
279 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
280 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
281 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
282 DeclRefExpr DRE(
283 const_cast<VarDecl *>(OrigVD),
284 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
285 OrigVD) != nullptr,
286 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
287 return EmitLValue(&DRE).getAddress();
288 });
289 // Check if the variable is also a firstprivate: in this case IInit is
290 // not generated. Initialization of this variable will happen in codegen
291 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000292 if (IInit) {
293 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
294 bool IsRegistered =
295 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
296 // Emit private VarDecl with copy init.
297 EmitDecl(*VD);
298 return GetAddrOfLocalVar(VD);
299 });
300 assert(IsRegistered &&
301 "lastprivate var already registered as private");
302 (void)IsRegistered;
303 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000304 }
305 ++IRef, ++IDestRef;
306 }
307 }
308 return HasAtLeastOneLastprivate;
309}
310
311void CodeGenFunction::EmitOMPLastprivateClauseFinal(
312 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
313 // Emit following code:
314 // if (<IsLastIterCond>) {
315 // orig_var1 = private_orig_var1;
316 // ...
317 // orig_varn = private_orig_varn;
318 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000319 llvm::BasicBlock *ThenBB = nullptr;
320 llvm::BasicBlock *DoneBB = nullptr;
321 if (IsLastIterCond) {
322 ThenBB = createBasicBlock(".omp.lastprivate.then");
323 DoneBB = createBasicBlock(".omp.lastprivate.done");
324 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
325 EmitBlock(ThenBB);
326 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000327 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
328 const Expr *LastIterVal = nullptr;
329 const Expr *IVExpr = nullptr;
330 const Expr *IncExpr = nullptr;
331 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000332 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
333 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
334 LoopDirective->getUpperBoundVariable())
335 ->getDecl())
336 ->getAnyInitializer();
337 IVExpr = LoopDirective->getIterationVariable();
338 IncExpr = LoopDirective->getInc();
339 auto IUpdate = LoopDirective->updates().begin();
340 for (auto *E : LoopDirective->counters()) {
341 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
342 LoopCountersAndUpdates[D] = *IUpdate;
343 ++IUpdate;
344 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000345 }
346 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000347 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000348 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000349 bool FirstLCV = true;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000350 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000351 auto *C = cast<OMPLastprivateClause>(*I);
352 auto IRef = C->varlist_begin();
353 auto ISrcRef = C->source_exprs().begin();
354 auto IDestRef = C->destination_exprs().begin();
355 for (auto *AssignOp : C->assignment_ops()) {
356 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000357 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000358 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
359 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
360 // If lastprivate variable is a loop control variable for loop-based
361 // directive, update its value before copyin back to original
362 // variable.
363 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000364 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000365 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
366 IVExpr->getType().getQualifiers(),
367 /*IsInitializer=*/false);
368 EmitIgnoredExpr(IncExpr);
369 FirstLCV = false;
370 }
371 EmitIgnoredExpr(UpExpr);
372 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000373 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
374 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
375 // Get the address of the original variable.
376 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
377 // Get the address of the private variable.
378 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000379 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD,
380 AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000381 }
382 ++IRef;
383 ++ISrcRef;
384 ++IDestRef;
385 }
386 }
387 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000388 if (IsLastIterCond) {
389 EmitBlock(DoneBB, /*IsFinished=*/true);
390 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000391}
392
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000393void CodeGenFunction::EmitOMPReductionClauseInit(
394 const OMPExecutableDirective &D,
395 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000396 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000397 auto *C = cast<OMPReductionClause>(*I);
398 auto ILHS = C->lhs_exprs().begin();
399 auto IRHS = C->rhs_exprs().begin();
400 for (auto IRef : C->varlists()) {
401 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
402 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
403 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
404 // Store the address of the original variable associated with the LHS
405 // implicit variable.
406 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
407 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
408 CapturedStmtInfo->lookup(OrigVD) != nullptr,
409 IRef->getType(), VK_LValue, IRef->getExprLoc());
410 return EmitLValue(&DRE).getAddress();
411 });
412 // Emit reduction copy.
413 bool IsRegistered =
414 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
415 // Emit private VarDecl with reduction init.
416 EmitDecl(*PrivateVD);
417 return GetAddrOfLocalVar(PrivateVD);
418 });
419 assert(IsRegistered && "private var already registered as private");
420 // Silence the warning about unused variable.
421 (void)IsRegistered;
422 ++ILHS, ++IRHS;
423 }
424 }
425}
426
427void CodeGenFunction::EmitOMPReductionClauseFinal(
428 const OMPExecutableDirective &D) {
429 llvm::SmallVector<const Expr *, 8> LHSExprs;
430 llvm::SmallVector<const Expr *, 8> RHSExprs;
431 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000432 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000433 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000434 HasAtLeastOneReduction = true;
435 auto *C = cast<OMPReductionClause>(*I);
436 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
437 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
438 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
439 }
440 if (HasAtLeastOneReduction) {
441 // Emit nowait reduction if nowait clause is present or directive is a
442 // parallel directive (it always has implicit barrier).
443 CGM.getOpenMPRuntime().emitReduction(
444 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
445 D.getSingleClause(OMPC_nowait) ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000446 isOpenMPParallelDirective(D.getDirectiveKind()) ||
447 D.getDirectiveKind() == OMPD_simd,
448 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000449 }
450}
451
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000452static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
453 const OMPExecutableDirective &S,
454 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000455 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000456 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
457 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
458 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000459 if (auto C = S.getSingleClause(OMPC_num_threads)) {
460 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
461 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
462 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
463 /*IgnoreResultAssign*/ true);
464 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
465 CGF, NumThreads, NumThreadsClause->getLocStart());
466 }
467 const Expr *IfCond = nullptr;
468 if (auto C = S.getSingleClause(OMPC_if)) {
469 IfCond = cast<OMPIfClause>(C)->getCondition();
470 }
471 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
472 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000473}
474
475void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
476 LexicalScope Scope(*this, S.getSourceRange());
477 // Emit parallel region as a standalone region.
478 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
479 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000480 bool Copyins = CGF.EmitOMPCopyinClause(S);
481 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
482 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000483 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000484 // initialization of firstprivate variables or propagation master's thread
485 // values of threadprivate variables to local instances of that variables
486 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000487 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
488 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000489 }
490 CGF.EmitOMPPrivateClause(S, PrivateScope);
491 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
492 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000493 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000494 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000495 // Emit implicit barrier at the end of the 'parallel' directive.
496 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
497 OMPD_unknown);
498 };
499 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000500}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000501
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000502void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000503 RunCleanupsScope BodyScope(*this);
504 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000505 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000506 EmitIgnoredExpr(I);
507 }
Alexander Musman3276a272015-03-21 10:12:56 +0000508 // Update the linear variables.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000509 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000510 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000511 for (auto U : C->updates()) {
512 EmitIgnoredExpr(U);
513 }
514 }
515
Alexander Musmana5f070a2014-10-01 06:03:56 +0000516 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000517 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
519 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000520 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521 // The end (updates/cleanups).
522 EmitBlock(Continue.getBlock());
523 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000524 // TODO: Update lastprivates if the SeparateIter flag is true.
525 // This will be implemented in a follow-up OMPLastprivateClause patch, but
526 // result should be still correct without it, as we do not make these
527 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000528}
529
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000530void CodeGenFunction::EmitOMPInnerLoop(
531 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
532 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000533 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
534 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000535 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000536
537 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000538 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000539 EmitBlock(CondBlock);
540 LoopStack.push(CondBlock);
541
542 // If there are any cleanups between here and the loop-exit scope,
543 // create a block to stage a loop exit along.
544 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000545 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000546 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000547
Alexander Musmand196ef22014-10-07 08:57:09 +0000548 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000549
Alexey Bataev2df54a02015-03-12 08:53:29 +0000550 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000551 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000552 if (ExitBlock != LoopExit.getBlock()) {
553 EmitBlock(ExitBlock);
554 EmitBranchThroughCleanup(LoopExit);
555 }
556
557 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000558 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000559
560 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000561 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000562 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
563
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000564 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000565
566 // Emit "IV = IV + 1" and a back-edge to the condition block.
567 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000568 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000569 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000570 BreakContinueStack.pop_back();
571 EmitBranch(CondBlock);
572 LoopStack.pop();
573 // Emit the fall-through block.
574 EmitBlock(LoopExit.getBlock());
575}
576
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000577void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000578 // Emit inits for the linear variables.
579 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
580 auto *C = cast<OMPLinearClause>(*I);
581 for (auto Init : C->inits()) {
582 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000583 auto *OrigVD = cast<VarDecl>(
584 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
585 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
586 CapturedStmtInfo->lookup(OrigVD) != nullptr,
587 VD->getInit()->getType(), VK_LValue,
588 VD->getInit()->getExprLoc());
589 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
590 EmitExprAsInit(&DRE, VD,
591 MakeAddrLValue(Emission.getAllocatedAddress(),
592 VD->getType(), Emission.Alignment),
593 /*capturedByInit=*/false);
594 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000595 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000596 // Emit the linear steps for the linear clauses.
597 // If a step is not constant, it is pre-calculated before the loop.
598 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
599 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000600 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000601 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000602 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000603 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000604 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000605}
606
607static void emitLinearClauseFinal(CodeGenFunction &CGF,
608 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000609 // Emit the final values of the linear variables.
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000610 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000611 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000612 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000613 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000614 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
615 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000616 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000617 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000618 auto *OrigAddr = CGF.EmitLValue(&DRE).getAddress();
619 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000620 VarScope.addPrivate(OrigVD,
621 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
622 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000623 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000624 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000625 }
626 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000627}
628
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000629static void emitAlignedClause(CodeGenFunction &CGF,
630 const OMPExecutableDirective &D) {
631 for (auto &&I = D.getClausesOfKind(OMPC_aligned); I; ++I) {
632 auto *Clause = cast<OMPAlignedClause>(*I);
633 unsigned ClauseAlignment = 0;
634 if (auto AlignmentExpr = Clause->getAlignment()) {
635 auto AlignmentCI =
636 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
637 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000638 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000639 for (auto E : Clause->varlists()) {
640 unsigned Alignment = ClauseAlignment;
641 if (Alignment == 0) {
642 // OpenMP [2.8.1, Description]
643 // If no optional parameter is specified, implementation-defined default
644 // alignments for SIMD instructions on the target platforms are assumed.
645 Alignment =
646 CGF.CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
647 E->getType());
648 }
649 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
650 "alignment is not power of 2");
651 if (Alignment != 0) {
652 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
653 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
654 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000655 }
656 }
657}
658
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000659static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000660 CodeGenFunction::OMPPrivateScope &LoopScope,
661 ArrayRef<Expr *> Counters) {
662 for (auto *E : Counters) {
663 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000664 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000665 // Emit var without initialization.
666 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
667 CGF.EmitAutoVarCleanups(VarEmission);
668 return VarEmission.getAllocatedAddress();
669 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000670 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000671}
672
Alexey Bataev62dbb972015-04-22 11:59:37 +0000673static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
674 const Expr *Cond, llvm::BasicBlock *TrueBlock,
675 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000676 {
677 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000678 emitPrivateLoopCounters(CGF, PreCondScope, S.counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000679 const VarDecl *IVDecl =
680 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
681 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
682 // Emit var without initialization.
683 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
684 CGF.EmitAutoVarCleanups(VarEmission);
685 return VarEmission.getAllocatedAddress();
686 });
687 assert(IsRegistered && "counter already registered as private");
688 // Silence the warning about unused variable.
689 (void)IsRegistered;
690 (void)PreCondScope.Privatize();
691 // Initialize internal counter to 0 to calculate initial values of real
692 // counters.
693 LValue IV = CGF.EmitLValue(S.getIterationVariable());
694 CGF.EmitStoreOfScalar(
695 llvm::ConstantInt::getNullValue(
696 IV.getAddress()->getType()->getPointerElementType()),
697 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
698 // Get initial values of real counters.
699 for (auto I : S.updates()) {
700 CGF.EmitIgnoredExpr(I);
701 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000702 }
703 // Check that loop is executed at least one time.
704 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
705}
706
Alexander Musman3276a272015-03-21 10:12:56 +0000707static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000708emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000709 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000710 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
711 auto *C = cast<OMPLinearClause>(*I);
712 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000713 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
714 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
715 // Emit var without initialization.
716 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
717 CGF.EmitAutoVarCleanups(VarEmission);
718 return VarEmission.getAllocatedAddress();
719 });
720 assert(IsRegistered && "linear var already registered as private");
721 // Silence the warning about unused variable.
722 (void)IsRegistered;
723 }
724 }
725}
726
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000727static void emitSafelenClause(CodeGenFunction &CGF,
728 const OMPExecutableDirective &D) {
729 if (auto *C =
730 cast_or_null<OMPSafelenClause>(D.getSingleClause(OMPC_safelen))) {
731 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
732 /*ignoreResult=*/true);
733 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
734 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
735 // In presence of finite 'safelen', it may be unsafe to mark all
736 // the memory instructions parallel, because loop-carried
737 // dependences of 'safelen' iterations are possible.
738 CGF.LoopStack.setParallel(false);
739 }
740}
741
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000742void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
743 // Walk clauses and process safelen/lastprivate.
744 LoopStack.setParallel();
745 LoopStack.setVectorizerEnable(true);
746 emitSafelenClause(*this, D);
747}
748
749void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
750 auto IC = D.counters().begin();
751 for (auto F : D.finals()) {
752 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000753 if (LocalDeclMap.lookup(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000754 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
755 CapturedStmtInfo->lookup(OrigVD) != nullptr,
756 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
757 auto *OrigAddr = EmitLValue(&DRE).getAddress();
758 OMPPrivateScope VarScope(*this);
759 VarScope.addPrivate(OrigVD,
760 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
761 (void)VarScope.Privatize();
762 EmitIgnoredExpr(F);
763 }
764 ++IC;
765 }
766 emitLinearClauseFinal(*this, D);
767}
768
Alexander Musman515ad8c2014-05-22 08:54:05 +0000769void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000770 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000771 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000772 // for (IV in 0..LastIteration) BODY;
773 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000774 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000775 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000776
Alexey Bataev62dbb972015-04-22 11:59:37 +0000777 // Emit: if (PreCond) - begin.
778 // If the condition constant folds and can be elided, avoid emitting the
779 // whole loop.
780 bool CondConstant;
781 llvm::BasicBlock *ContBlock = nullptr;
782 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
783 if (!CondConstant)
784 return;
785 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000786 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
787 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000788 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
789 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000790 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000791 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000792 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000793
794 // Emit the loop iteration variable.
795 const Expr *IVExpr = S.getIterationVariable();
796 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
797 CGF.EmitVarDecl(*IVDecl);
798 CGF.EmitIgnoredExpr(S.getInit());
799
800 // Emit the iterations count variable.
801 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000802 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000803 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
804 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
805 // Emit calculation of the iterations count.
806 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000807 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000808
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000809 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000810
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000811 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000812 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000813 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000814 {
815 OMPPrivateScope LoopScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000816 emitPrivateLoopCounters(CGF, LoopScope, S.counters());
817 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000818 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000819 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000820 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000821 (void)LoopScope.Privatize();
822 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
Alexey Bataevae05c292015-06-16 11:59:36 +0000823 S.getCond(), S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000824 [&S](CodeGenFunction &CGF) {
825 CGF.EmitOMPLoopBody(S);
826 CGF.EmitStopPoint(&S);
827 },
828 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000829 // Emit final copy of the lastprivate variables at the end of loops.
830 if (HasLastprivateClause) {
831 CGF.EmitOMPLastprivateClauseFinal(S);
832 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000833 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000834 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000835 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000836 // Emit: if (PreCond) - end.
837 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000838 CGF.EmitBranch(ContBlock);
839 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000840 }
841 };
842 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000843}
844
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000845void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
846 const OMPLoopDirective &S,
847 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000848 bool Ordered, llvm::Value *LB,
849 llvm::Value *UB, llvm::Value *ST,
850 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000851 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000852
853 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000854 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000855
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000856 assert((Ordered ||
857 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000858 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000859
860 // Emit outer loop.
861 //
862 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000863 // When schedule(dynamic,chunk_size) is specified, the iterations are
864 // distributed to threads in the team in chunks as the threads request them.
865 // Each thread executes a chunk of iterations, then requests another chunk,
866 // until no chunks remain to be distributed. Each chunk contains chunk_size
867 // iterations, except for the last chunk to be distributed, which may have
868 // fewer iterations. When no chunk_size is specified, it defaults to 1.
869 //
870 // When schedule(guided,chunk_size) is specified, the iterations are assigned
871 // to threads in the team in chunks as the executing threads request them.
872 // Each thread executes a chunk of iterations, then requests another chunk,
873 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
874 // each chunk is proportional to the number of unassigned iterations divided
875 // by the number of threads in the team, decreasing to 1. For a chunk_size
876 // with value k (greater than 1), the size of each chunk is determined in the
877 // same way, with the restriction that the chunks do not contain fewer than k
878 // iterations (except for the last chunk to be assigned, which may have fewer
879 // than k iterations).
880 //
881 // When schedule(auto) is specified, the decision regarding scheduling is
882 // delegated to the compiler and/or runtime system. The programmer gives the
883 // implementation the freedom to choose any possible mapping of iterations to
884 // threads in the team.
885 //
886 // When schedule(runtime) is specified, the decision regarding scheduling is
887 // deferred until run time, and the schedule and chunk size are taken from the
888 // run-sched-var ICV. If the ICV is set to auto, the schedule is
889 // implementation defined
890 //
891 // while(__kmpc_dispatch_next(&LB, &UB)) {
892 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000893 // while (idx <= UB) { BODY; ++idx;
894 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
895 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000896 // }
897 //
898 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000899 // When schedule(static, chunk_size) is specified, iterations are divided into
900 // chunks of size chunk_size, and the chunks are assigned to the threads in
901 // the team in a round-robin fashion in the order of the thread number.
902 //
903 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
904 // while (idx <= UB) { BODY; ++idx; } // inner loop
905 // LB = LB + ST;
906 // UB = UB + ST;
907 // }
908 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000909
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000910 const Expr *IVExpr = S.getIterationVariable();
911 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
912 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
913
Alexander Musman92bdaab2015-03-12 13:37:50 +0000914 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000915 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
916 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
917 : UB),
918 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000919
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000920 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
921
922 // Start the loop with a block that tests the condition.
923 auto CondBlock = createBasicBlock("omp.dispatch.cond");
924 EmitBlock(CondBlock);
925 LoopStack.push(CondBlock);
926
927 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000928 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000929 // UB = min(UB, GlobalUB)
930 EmitIgnoredExpr(S.getEnsureUpperBound());
931 // IV = LB
932 EmitIgnoredExpr(S.getInit());
933 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +0000934 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +0000935 } else {
936 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
937 IL, LB, UB, ST);
938 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000939
940 // If there are any cleanups between here and the loop-exit scope,
941 // create a block to stage a loop exit along.
942 auto ExitBlock = LoopExit.getBlock();
943 if (LoopScope.requiresCleanups())
944 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
945
946 auto LoopBody = createBasicBlock("omp.dispatch.body");
947 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
948 if (ExitBlock != LoopExit.getBlock()) {
949 EmitBlock(ExitBlock);
950 EmitBranchThroughCleanup(LoopExit);
951 }
952 EmitBlock(LoopBody);
953
Alexander Musman92bdaab2015-03-12 13:37:50 +0000954 // Emit "IV = LB" (in case of static schedule, we have already calculated new
955 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000956 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000957 EmitIgnoredExpr(S.getInit());
958
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000959 // Create a block for the increment.
960 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
961 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
962
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000963 // Generate !llvm.loop.parallel metadata for loads and stores for loops
964 // with dynamic/guided scheduling and without ordered clause.
965 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
966 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
967 ScheduleKind == OMPC_SCHEDULE_guided) &&
968 !Ordered);
969 } else {
970 EmitOMPSimdInit(S);
971 }
972
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000973 SourceLocation Loc = S.getLocStart();
974 EmitOMPInnerLoop(
Alexey Bataevae05c292015-06-16 11:59:36 +0000975 S, LoopScope.requiresCleanups(), S.getCond(),
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000976 S.getInc(),
977 [&S](CodeGenFunction &CGF) {
978 CGF.EmitOMPLoopBody(S);
979 CGF.EmitStopPoint(&S);
980 },
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000981 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
982 if (Ordered) {
983 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000984 CGF, Loc, IVSize, IVSigned);
985 }
986 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000987
988 EmitBlock(Continue.getBlock());
989 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000990 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000991 // Emit "LB = LB + Stride", "UB = UB + Stride".
992 EmitIgnoredExpr(S.getNextLowerBound());
993 EmitIgnoredExpr(S.getNextUpperBound());
994 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000995
996 EmitBranch(CondBlock);
997 LoopStack.pop();
998 // Emit the fall-through block.
999 EmitBlock(LoopExit.getBlock());
1000
1001 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001002 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001003 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001004}
1005
Alexander Musmanc6388682014-12-15 07:07:06 +00001006/// \brief Emit a helper variable and return corresponding lvalue.
1007static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1008 const DeclRefExpr *Helper) {
1009 auto VDecl = cast<VarDecl>(Helper->getDecl());
1010 CGF.EmitVarDecl(*VDecl);
1011 return CGF.EmitLValue(Helper);
1012}
1013
Alexey Bataev040d5402015-05-12 08:35:28 +00001014static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1015emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1016 bool OuterRegion) {
1017 // Detect the loop schedule kind and chunk.
1018 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1019 llvm::Value *Chunk = nullptr;
1020 if (auto *C =
1021 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
1022 ScheduleKind = C->getScheduleKind();
1023 if (const auto *Ch = C->getChunkSize()) {
1024 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1025 if (OuterRegion) {
1026 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1027 CGF.EmitVarDecl(*ImpVar);
1028 CGF.EmitStoreThroughLValue(
1029 CGF.EmitAnyExpr(Ch),
1030 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1031 ImpVar->getType()));
1032 } else {
1033 Ch = ImpRef;
1034 }
1035 }
1036 if (!C->getHelperChunkSize() || !OuterRegion) {
1037 Chunk = CGF.EmitScalarExpr(Ch);
1038 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
1039 S.getIterationVariable()->getType());
1040 }
1041 }
1042 }
1043 return std::make_pair(Chunk, ScheduleKind);
1044}
1045
Alexey Bataev38e89532015-04-16 04:54:05 +00001046bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001047 // Emit the loop iteration variable.
1048 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1049 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1050 EmitVarDecl(*IVDecl);
1051
1052 // Emit the iterations count variable.
1053 // If it is not a variable, Sema decided to calculate iterations count on each
1054 // iteration (e.g., it is foldable into a constant).
1055 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1056 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1057 // Emit calculation of the iterations count.
1058 EmitIgnoredExpr(S.getCalcLastIteration());
1059 }
1060
1061 auto &RT = CGM.getOpenMPRuntime();
1062
Alexey Bataev38e89532015-04-16 04:54:05 +00001063 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001064 // Check pre-condition.
1065 {
1066 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001067 // If the condition constant folds and can be elided, avoid emitting the
1068 // whole loop.
1069 bool CondConstant;
1070 llvm::BasicBlock *ContBlock = nullptr;
1071 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1072 if (!CondConstant)
1073 return false;
1074 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001075 auto *ThenBlock = createBasicBlock("omp.precond.then");
1076 ContBlock = createBasicBlock("omp.precond.end");
1077 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001078 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001079 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001080 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001081 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001082
1083 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001084 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001085 // Emit 'then' code.
1086 {
1087 // Emit helper vars inits.
1088 LValue LB =
1089 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1090 LValue UB =
1091 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1092 LValue ST =
1093 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1094 LValue IL =
1095 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1096
1097 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001098 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1099 // Emit implicit barrier to synchronize threads and avoid data races on
1100 // initialization of firstprivate variables.
1101 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1102 OMPD_unknown);
1103 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001104 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001106 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001107 emitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001108 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001109 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001110
1111 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001112 llvm::Value *Chunk;
1113 OpenMPScheduleClauseKind ScheduleKind;
1114 auto ScheduleInfo =
1115 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1116 Chunk = ScheduleInfo.first;
1117 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001118 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1119 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001120 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001121 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001122 /* Chunked */ Chunk != nullptr) &&
1123 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001124 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1125 EmitOMPSimdInit(S);
1126 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001127 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1128 // When no chunk_size is specified, the iteration space is divided into
1129 // chunks that are approximately equal in size, and at most one chunk is
1130 // distributed to each thread. Note that the size of the chunks is
1131 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001132 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001133 Ordered, IL.getAddress(), LB.getAddress(),
1134 UB.getAddress(), ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001135 // UB = min(UB, GlobalUB);
1136 EmitIgnoredExpr(S.getEnsureUpperBound());
1137 // IV = LB;
1138 EmitIgnoredExpr(S.getInit());
1139 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001140 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1141 S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001142 [&S](CodeGenFunction &CGF) {
1143 CGF.EmitOMPLoopBody(S);
1144 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001145 },
1146 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001147 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001148 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001149 } else {
1150 // Emit the outer loop, which requests its work chunk [LB..UB] from
1151 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001152 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1153 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1154 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001155 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001156 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001157 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1158 if (HasLastprivateClause)
1159 EmitOMPLastprivateClauseFinal(
1160 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001161 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001162 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1163 EmitOMPSimdFinal(S);
1164 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001165 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001166 if (ContBlock) {
1167 EmitBranch(ContBlock);
1168 EmitBlock(ContBlock, true);
1169 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001170 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001171 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001172}
1173
1174void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001176 bool HasLastprivates = false;
1177 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1178 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1179 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001181
1182 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001183 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001184 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1185 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001186}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001187
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001188void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1189 LexicalScope Scope(*this, S.getSourceRange());
1190 bool HasLastprivates = false;
1191 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1192 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1193 };
1194 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
1195
1196 // Emit an implicit barrier at the end.
1197 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
1198 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1199 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001200}
1201
Alexey Bataev2df54a02015-03-12 08:53:29 +00001202static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1203 const Twine &Name,
1204 llvm::Value *Init = nullptr) {
1205 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1206 if (Init)
1207 CGF.EmitScalarInit(Init, LVal);
1208 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001209}
1210
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001211static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1212 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001213 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1214 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1215 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001216 bool HasLastprivates = false;
1217 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001218 auto &C = CGF.CGM.getContext();
1219 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1220 // Emit helper vars inits.
1221 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1222 CGF.Builder.getInt32(0));
1223 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1224 LValue UB =
1225 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1226 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1227 CGF.Builder.getInt32(1));
1228 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1229 CGF.Builder.getInt32(0));
1230 // Loop counter.
1231 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1232 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001233 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001234 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001235 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001236 // Generate condition for loop.
1237 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1238 OK_Ordinary, S.getLocStart(),
1239 /*fpContractable=*/false);
1240 // Increment for loop counter.
1241 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1242 OK_Ordinary, S.getLocStart());
1243 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1244 // Iterate through all sections and emit a switch construct:
1245 // switch (IV) {
1246 // case 0:
1247 // <SectionStmt[0]>;
1248 // break;
1249 // ...
1250 // case <NumSection> - 1:
1251 // <SectionStmt[<NumSection> - 1]>;
1252 // break;
1253 // }
1254 // .omp.sections.exit:
1255 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1256 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1257 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1258 CS->size());
1259 unsigned CaseNumber = 0;
1260 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1261 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1262 CGF.EmitBlock(CaseBB);
1263 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1264 CGF.EmitStmt(*C);
1265 CGF.EmitBranch(ExitBB);
1266 }
1267 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1268 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001269
1270 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1271 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1272 // Emit implicit barrier to synchronize threads and avoid data races on
1273 // initialization of firstprivate variables.
1274 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1275 OMPD_unknown);
1276 }
Alexey Bataev73870832015-04-27 04:12:12 +00001277 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001278 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001279 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001280 (void)LoopScope.Privatize();
1281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 // Emit static non-chunked loop.
1283 CGF.CGM.getOpenMPRuntime().emitForInit(
1284 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001285 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1286 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001287 // UB = min(UB, GlobalUB);
1288 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1289 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1290 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1291 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1292 // IV = LB;
1293 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1294 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001295 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1296 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001297 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001298 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001299 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001300
1301 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1302 if (HasLastprivates)
1303 CGF.EmitOMPLastprivateClauseFinal(
1304 S, CGF.Builder.CreateIsNotNull(
1305 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001306 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001307
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001308 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001309 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1310 // clause. Otherwise the barrier will be generated by the codegen for the
1311 // directive.
1312 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1313 // Emit implicit barrier to synchronize threads and avoid data races on
1314 // initialization of firstprivate variables.
1315 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1316 OMPD_unknown);
1317 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001318 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001319 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001320 // If only one section is found - no need to generate loop, emit as a single
1321 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001322 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001323 // No need to generate reductions for sections with single section region, we
1324 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001325 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001326 // No need to generate lastprivates for sections with single section region,
1327 // we can use original shared variable for all calculations with barrier at
1328 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001329 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001330 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1331 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1332 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001333 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001334 (void)SingleScope.Privatize();
1335
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001336 CGF.EmitStmt(Stmt);
1337 CGF.EnsureInsertPoint();
1338 };
1339 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1340 llvm::None, llvm::None,
1341 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001342 // Emit barrier for firstprivates, lastprivates or reductions only if
1343 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1344 // generated by the codegen for the directive.
1345 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1346 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001347 // Emit implicit barrier to synchronize threads and avoid data races on
1348 // initialization of firstprivate variables.
1349 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1350 OMPD_unknown);
1351 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001352 return OMPD_single;
1353}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001354
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001355void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1356 LexicalScope Scope(*this, S.getSourceRange());
1357 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001358 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001359 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001360 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001361 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001362}
1363
1364void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001365 LexicalScope Scope(*this, S.getSourceRange());
1366 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1367 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1368 CGF.EnsureInsertPoint();
1369 };
1370 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001371}
1372
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001373void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001374 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001375 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001376 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001377 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001378 // Check if there are any 'copyprivate' clauses associated with this
1379 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001380 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001381 // Build a list of copyprivate variables along with helper expressions
1382 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001383 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001384 auto *C = cast<OMPCopyprivateClause>(*I);
1385 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001386 DestExprs.append(C->destination_exprs().begin(),
1387 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001388 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001389 AssignmentOps.append(C->assignment_ops().begin(),
1390 C->assignment_ops().end());
1391 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001393 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001394 bool HasFirstprivates;
1395 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1396 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1397 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001398 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001399 (void)SingleScope.Privatize();
1400
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001401 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1402 CGF.EnsureInsertPoint();
1403 };
1404 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001405 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001406 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001407 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1408 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1409 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1410 CopyprivateVars.empty()) {
1411 CGM.getOpenMPRuntime().emitBarrierCall(
1412 *this, S.getLocStart(),
1413 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001414 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001415}
1416
Alexey Bataev8d690652014-12-04 07:23:53 +00001417void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001418 LexicalScope Scope(*this, S.getSourceRange());
1419 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1420 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1421 CGF.EnsureInsertPoint();
1422 };
1423 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001424}
1425
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001426void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001427 LexicalScope Scope(*this, S.getSourceRange());
1428 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1429 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1430 CGF.EnsureInsertPoint();
1431 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001432 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001433 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001434}
1435
Alexey Bataev671605e2015-04-13 05:28:11 +00001436void CodeGenFunction::EmitOMPParallelForDirective(
1437 const OMPParallelForDirective &S) {
1438 // Emit directive as a combined directive that consists of two implicit
1439 // directives: 'parallel' with 'for' directive.
1440 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001441 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001442 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1443 CGF.EmitOMPWorksharingLoop(S);
1444 // Emit implicit barrier at the end of parallel region, but this barrier
1445 // is at the end of 'for' directive, so emit it as the implicit barrier for
1446 // this 'for' directive.
1447 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1448 OMPD_parallel);
1449 };
1450 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001451}
1452
Alexander Musmane4e893b2014-09-23 09:33:00 +00001453void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001454 const OMPParallelForSimdDirective &S) {
1455 // Emit directive as a combined directive that consists of two implicit
1456 // directives: 'parallel' with 'for' directive.
1457 LexicalScope Scope(*this, S.getSourceRange());
1458 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1459 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1460 CGF.EmitOMPWorksharingLoop(S);
1461 // Emit implicit barrier at the end of parallel region, but this barrier
1462 // is at the end of 'for' directive, so emit it as the implicit barrier for
1463 // this 'for' directive.
1464 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1465 OMPD_parallel);
1466 };
1467 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001468}
1469
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001470void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001471 const OMPParallelSectionsDirective &S) {
1472 // Emit directive as a combined directive that consists of two implicit
1473 // directives: 'parallel' with 'sections' directive.
1474 LexicalScope Scope(*this, S.getSourceRange());
1475 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1476 (void)emitSections(CGF, S);
1477 // Emit implicit barrier at the end of parallel region.
1478 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1479 OMPD_parallel);
1480 };
1481 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001482}
1483
Alexey Bataev62b63b12015-03-10 07:28:44 +00001484void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1485 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001486 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001487 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1488 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1489 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001490 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001491 // The first function argument for tasks is a thread id, the second one is a
1492 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001493 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1494 // Get list of private variables.
1495 llvm::SmallVector<const Expr *, 8> PrivateVars;
1496 llvm::SmallVector<const Expr *, 8> PrivateCopies;
1497 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1498 auto *C = cast<OMPPrivateClause>(*I);
1499 auto IRef = C->varlist_begin();
1500 for (auto *IInit : C->private_copies()) {
1501 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1502 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1503 PrivateVars.push_back(*IRef);
1504 PrivateCopies.push_back(IInit);
1505 }
1506 ++IRef;
1507 }
1508 }
1509 EmittedAsPrivate.clear();
1510 // Get list of firstprivate variables.
1511 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1512 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1513 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1514 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1515 auto *C = cast<OMPFirstprivateClause>(*I);
1516 auto IRef = C->varlist_begin();
1517 auto IElemInitRef = C->inits().begin();
1518 for (auto *IInit : C->private_copies()) {
1519 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1520 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1521 FirstprivateVars.push_back(*IRef);
1522 FirstprivateCopies.push_back(IInit);
1523 FirstprivateInits.push_back(*IElemInitRef);
1524 }
1525 ++IRef, ++IElemInitRef;
1526 }
1527 }
1528 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1529 CodeGenFunction &CGF) {
1530 // Set proper addresses for generated private copies.
1531 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1532 OMPPrivateScope Scope(CGF);
1533 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
1534 auto *CopyFn = CGF.Builder.CreateAlignedLoad(
1535 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)),
1536 CGF.PointerAlignInBytes);
1537 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad(
1538 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)),
1539 CGF.PointerAlignInBytes);
1540 // Map privates.
1541 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16>
1542 PrivatePtrs;
1543 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1544 CallArgs.push_back(PrivatesPtr);
1545 for (auto *E : PrivateVars) {
1546 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1547 auto *PrivatePtr =
1548 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1549 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1550 CallArgs.push_back(PrivatePtr);
1551 }
1552 for (auto *E : FirstprivateVars) {
1553 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1554 auto *PrivatePtr =
1555 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1556 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1557 CallArgs.push_back(PrivatePtr);
1558 }
1559 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1560 for (auto &&Pair : PrivatePtrs) {
1561 auto *Replacement =
1562 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes);
1563 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1564 }
1565 }
1566 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001567 if (*PartId) {
1568 // TODO: emit code for untied tasks.
1569 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001570 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001571 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001572 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001573 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001574 // Check if we should emit tied or untied task.
1575 bool Tied = !S.getSingleClause(OMPC_untied);
1576 // Check if the task is final
1577 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1578 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1579 // If the condition constant folds and can be elided, try to avoid emitting
1580 // the condition and the dead arm of the if/else.
1581 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1582 bool CondConstant;
1583 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1584 Final.setInt(CondConstant);
1585 else
1586 Final.setPointer(EvaluateExprAsBool(Cond));
1587 } else {
1588 // By default the task is not final.
1589 Final.setInt(/*IntVal=*/false);
1590 }
1591 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001592 const Expr *IfCond = nullptr;
1593 if (auto C = S.getSingleClause(OMPC_if)) {
1594 IfCond = cast<OMPIfClause>(C)->getCondition();
1595 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001596 CGM.getOpenMPRuntime().emitTaskCall(
1597 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001598 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev9e034042015-05-05 04:05:12 +00001599 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001600}
1601
Alexey Bataev9f797f32015-02-05 05:57:51 +00001602void CodeGenFunction::EmitOMPTaskyieldDirective(
1603 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001604 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001605}
1606
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001607void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001608 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001609}
1610
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001611void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1612 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001613}
1614
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001615void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001616 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1617 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1618 auto FlushClause = cast<OMPFlushClause>(C);
1619 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1620 FlushClause->varlist_end());
1621 }
1622 return llvm::None;
1623 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001624}
1625
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001626void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1627 LexicalScope Scope(*this, S.getSourceRange());
1628 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1629 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1630 CGF.EnsureInsertPoint();
1631 };
1632 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001633}
1634
Alexey Bataevb57056f2015-01-22 06:17:56 +00001635static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1636 QualType SrcType, QualType DestType) {
1637 assert(CGF.hasScalarEvaluationKind(DestType) &&
1638 "DestType must have scalar evaluation kind.");
1639 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1640 return Val.isScalar()
1641 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1642 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1643 DestType);
1644}
1645
1646static CodeGenFunction::ComplexPairTy
1647convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1648 QualType DestType) {
1649 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1650 "DestType must have complex evaluation kind.");
1651 CodeGenFunction::ComplexPairTy ComplexVal;
1652 if (Val.isScalar()) {
1653 // Convert the input element to the element type of the complex.
1654 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1655 auto ScalarVal =
1656 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1657 ComplexVal = CodeGenFunction::ComplexPairTy(
1658 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1659 } else {
1660 assert(Val.isComplex() && "Must be a scalar or complex.");
1661 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1662 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1663 ComplexVal.first = CGF.EmitScalarConversion(
1664 Val.getComplexVal().first, SrcElementType, DestElementType);
1665 ComplexVal.second = CGF.EmitScalarConversion(
1666 Val.getComplexVal().second, SrcElementType, DestElementType);
1667 }
1668 return ComplexVal;
1669}
1670
Alexey Bataev5e018f92015-04-23 06:35:10 +00001671static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1672 LValue LVal, RValue RVal) {
1673 if (LVal.isGlobalReg()) {
1674 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1675 } else {
1676 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1677 : llvm::Monotonic,
1678 LVal.isVolatile(), /*IsInit=*/false);
1679 }
1680}
1681
1682static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1683 QualType RValTy) {
1684 switch (CGF.getEvaluationKind(LVal.getType())) {
1685 case TEK_Scalar:
1686 CGF.EmitStoreThroughLValue(
1687 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1688 LVal);
1689 break;
1690 case TEK_Complex:
1691 CGF.EmitStoreOfComplex(
1692 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1693 /*isInit=*/false);
1694 break;
1695 case TEK_Aggregate:
1696 llvm_unreachable("Must be a scalar or complex.");
1697 }
1698}
1699
Alexey Bataevb57056f2015-01-22 06:17:56 +00001700static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1701 const Expr *X, const Expr *V,
1702 SourceLocation Loc) {
1703 // v = x;
1704 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1705 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1706 LValue XLValue = CGF.EmitLValue(X);
1707 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001708 RValue Res = XLValue.isGlobalReg()
1709 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1710 : CGF.EmitAtomicLoad(XLValue, Loc,
1711 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001712 : llvm::Monotonic,
1713 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001714 // OpenMP, 2.12.6, atomic Construct
1715 // Any atomic construct with a seq_cst clause forces the atomically
1716 // performed operation to include an implicit flush operation without a
1717 // list.
1718 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001719 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001720 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001721}
1722
Alexey Bataevb8329262015-02-27 06:33:30 +00001723static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1724 const Expr *X, const Expr *E,
1725 SourceLocation Loc) {
1726 // x = expr;
1727 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001728 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001729 // OpenMP, 2.12.6, atomic Construct
1730 // Any atomic construct with a seq_cst clause forces the atomically
1731 // performed operation to include an implicit flush operation without a
1732 // list.
1733 if (IsSeqCst)
1734 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1735}
1736
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001737static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1738 RValue Update,
1739 BinaryOperatorKind BO,
1740 llvm::AtomicOrdering AO,
1741 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001742 auto &Context = CGF.CGM.getContext();
1743 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001744 // expression is simple and atomic is allowed for the given type for the
1745 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001746 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001747 !Update.getScalarVal()->getType()->isIntegerTy() ||
1748 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1749 (Update.getScalarVal()->getType() !=
1750 X.getAddress()->getType()->getPointerElementType())) ||
1751 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001752 !Context.getTargetInfo().hasBuiltinAtomic(
1753 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001754 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001755
1756 llvm::AtomicRMWInst::BinOp RMWOp;
1757 switch (BO) {
1758 case BO_Add:
1759 RMWOp = llvm::AtomicRMWInst::Add;
1760 break;
1761 case BO_Sub:
1762 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001763 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001764 RMWOp = llvm::AtomicRMWInst::Sub;
1765 break;
1766 case BO_And:
1767 RMWOp = llvm::AtomicRMWInst::And;
1768 break;
1769 case BO_Or:
1770 RMWOp = llvm::AtomicRMWInst::Or;
1771 break;
1772 case BO_Xor:
1773 RMWOp = llvm::AtomicRMWInst::Xor;
1774 break;
1775 case BO_LT:
1776 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1777 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1778 : llvm::AtomicRMWInst::Max)
1779 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1780 : llvm::AtomicRMWInst::UMax);
1781 break;
1782 case BO_GT:
1783 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1784 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1785 : llvm::AtomicRMWInst::Min)
1786 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1787 : llvm::AtomicRMWInst::UMin);
1788 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001789 case BO_Assign:
1790 RMWOp = llvm::AtomicRMWInst::Xchg;
1791 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001792 case BO_Mul:
1793 case BO_Div:
1794 case BO_Rem:
1795 case BO_Shl:
1796 case BO_Shr:
1797 case BO_LAnd:
1798 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001799 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001800 case BO_PtrMemD:
1801 case BO_PtrMemI:
1802 case BO_LE:
1803 case BO_GE:
1804 case BO_EQ:
1805 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001806 case BO_AddAssign:
1807 case BO_SubAssign:
1808 case BO_AndAssign:
1809 case BO_OrAssign:
1810 case BO_XorAssign:
1811 case BO_MulAssign:
1812 case BO_DivAssign:
1813 case BO_RemAssign:
1814 case BO_ShlAssign:
1815 case BO_ShrAssign:
1816 case BO_Comma:
1817 llvm_unreachable("Unsupported atomic update operation");
1818 }
1819 auto *UpdateVal = Update.getScalarVal();
1820 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1821 UpdateVal = CGF.Builder.CreateIntCast(
1822 IC, X.getAddress()->getType()->getPointerElementType(),
1823 X.getType()->hasSignedIntegerRepresentation());
1824 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001825 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1826 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001827}
1828
Alexey Bataev5e018f92015-04-23 06:35:10 +00001829std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001830 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1831 llvm::AtomicOrdering AO, SourceLocation Loc,
1832 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1833 // Update expressions are allowed to have the following forms:
1834 // x binop= expr; -> xrval + expr;
1835 // x++, ++x -> xrval + 1;
1836 // x--, --x -> xrval - 1;
1837 // x = x binop expr; -> xrval binop expr
1838 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001839 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1840 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001841 if (X.isGlobalReg()) {
1842 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1843 // 'xrval'.
1844 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1845 } else {
1846 // Perform compare-and-swap procedure.
1847 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001848 }
1849 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001850 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001851}
1852
1853static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1854 const Expr *X, const Expr *E,
1855 const Expr *UE, bool IsXLHSInRHSPart,
1856 SourceLocation Loc) {
1857 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1858 "Update expr in 'atomic update' must be a binary operator.");
1859 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1860 // Update expressions are allowed to have the following forms:
1861 // x binop= expr; -> xrval + expr;
1862 // x++, ++x -> xrval + 1;
1863 // x--, --x -> xrval - 1;
1864 // x = x binop expr; -> xrval binop expr
1865 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001866 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001867 LValue XLValue = CGF.EmitLValue(X);
1868 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001869 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001870 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1871 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1872 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1873 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1874 auto Gen =
1875 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1876 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1877 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1878 return CGF.EmitAnyExpr(UE);
1879 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001880 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1881 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1882 // OpenMP, 2.12.6, atomic Construct
1883 // Any atomic construct with a seq_cst clause forces the atomically
1884 // performed operation to include an implicit flush operation without a
1885 // list.
1886 if (IsSeqCst)
1887 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1888}
1889
1890static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1891 QualType SourceType, QualType ResType) {
1892 switch (CGF.getEvaluationKind(ResType)) {
1893 case TEK_Scalar:
1894 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1895 case TEK_Complex: {
1896 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1897 return RValue::getComplex(Res.first, Res.second);
1898 }
1899 case TEK_Aggregate:
1900 break;
1901 }
1902 llvm_unreachable("Must be a scalar or complex.");
1903}
1904
1905static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1906 bool IsPostfixUpdate, const Expr *V,
1907 const Expr *X, const Expr *E,
1908 const Expr *UE, bool IsXLHSInRHSPart,
1909 SourceLocation Loc) {
1910 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1911 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1912 RValue NewVVal;
1913 LValue VLValue = CGF.EmitLValue(V);
1914 LValue XLValue = CGF.EmitLValue(X);
1915 RValue ExprRValue = CGF.EmitAnyExpr(E);
1916 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1917 QualType NewVValType;
1918 if (UE) {
1919 // 'x' is updated with some additional value.
1920 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1921 "Update expr in 'atomic capture' must be a binary operator.");
1922 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1923 // Update expressions are allowed to have the following forms:
1924 // x binop= expr; -> xrval + expr;
1925 // x++, ++x -> xrval + 1;
1926 // x--, --x -> xrval - 1;
1927 // x = x binop expr; -> xrval binop expr
1928 // x = expr Op x; - > expr binop xrval;
1929 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1930 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1931 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1932 NewVValType = XRValExpr->getType();
1933 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1934 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1935 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1936 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1937 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1938 RValue Res = CGF.EmitAnyExpr(UE);
1939 NewVVal = IsPostfixUpdate ? XRValue : Res;
1940 return Res;
1941 };
1942 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1943 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1944 if (Res.first) {
1945 // 'atomicrmw' instruction was generated.
1946 if (IsPostfixUpdate) {
1947 // Use old value from 'atomicrmw'.
1948 NewVVal = Res.second;
1949 } else {
1950 // 'atomicrmw' does not provide new value, so evaluate it using old
1951 // value of 'x'.
1952 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1953 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1954 NewVVal = CGF.EmitAnyExpr(UE);
1955 }
1956 }
1957 } else {
1958 // 'x' is simply rewritten with some 'expr'.
1959 NewVValType = X->getType().getNonReferenceType();
1960 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1961 X->getType().getNonReferenceType());
1962 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1963 NewVVal = XRValue;
1964 return ExprRValue;
1965 };
1966 // Try to perform atomicrmw xchg, otherwise simple exchange.
1967 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1968 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1969 Loc, Gen);
1970 if (Res.first) {
1971 // 'atomicrmw' instruction was generated.
1972 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1973 }
1974 }
1975 // Emit post-update store to 'v' of old/new 'x' value.
1976 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001977 // OpenMP, 2.12.6, atomic Construct
1978 // Any atomic construct with a seq_cst clause forces the atomically
1979 // performed operation to include an implicit flush operation without a
1980 // list.
1981 if (IsSeqCst)
1982 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1983}
1984
Alexey Bataevb57056f2015-01-22 06:17:56 +00001985static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001986 bool IsSeqCst, bool IsPostfixUpdate,
1987 const Expr *X, const Expr *V, const Expr *E,
1988 const Expr *UE, bool IsXLHSInRHSPart,
1989 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001990 switch (Kind) {
1991 case OMPC_read:
1992 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1993 break;
1994 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001995 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1996 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001997 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001998 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001999 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2000 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002001 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002002 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2003 IsXLHSInRHSPart, Loc);
2004 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002005 case OMPC_if:
2006 case OMPC_final:
2007 case OMPC_num_threads:
2008 case OMPC_private:
2009 case OMPC_firstprivate:
2010 case OMPC_lastprivate:
2011 case OMPC_reduction:
2012 case OMPC_safelen:
2013 case OMPC_collapse:
2014 case OMPC_default:
2015 case OMPC_seq_cst:
2016 case OMPC_shared:
2017 case OMPC_linear:
2018 case OMPC_aligned:
2019 case OMPC_copyin:
2020 case OMPC_copyprivate:
2021 case OMPC_flush:
2022 case OMPC_proc_bind:
2023 case OMPC_schedule:
2024 case OMPC_ordered:
2025 case OMPC_nowait:
2026 case OMPC_untied:
2027 case OMPC_threadprivate:
2028 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002029 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2030 }
2031}
2032
2033void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
2034 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
2035 OpenMPClauseKind Kind = OMPC_unknown;
2036 for (auto *C : S.clauses()) {
2037 // Find first clause (skip seq_cst clause, if it is first).
2038 if (C->getClauseKind() != OMPC_seq_cst) {
2039 Kind = C->getClauseKind();
2040 break;
2041 }
2042 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002043
2044 const auto *CS =
2045 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002046 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002047 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002048 }
2049 // Processing for statements under 'atomic capture'.
2050 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2051 for (const auto *C : Compound->body()) {
2052 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2053 enterFullExpression(EWC);
2054 }
2055 }
2056 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002057
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002058 LexicalScope Scope(*this, S.getSourceRange());
2059 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002060 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2061 S.getV(), S.getExpr(), S.getUpdateExpr(),
2062 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002063 };
2064 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002065}
2066
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002067void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2068 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2069}
2070
Alexey Bataev13314bf2014-10-09 04:18:56 +00002071void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2072 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2073}