blob: 4f13b2221bfa51b5b5c901692373f7fba5d23f0b [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 Bataevcbdcbb72015-06-17 07:45:51 +0000577static void emitLinearClauseInit(CodeGenFunction &CGF,
578 const OMPLoopDirective &D) {
579 // Emit inits for the linear variables.
580 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
581 auto *C = cast<OMPLinearClause>(*I);
582 for (auto Init : C->inits()) {
583 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
584 CGF.EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000585 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000586 // Emit the linear steps for the linear clauses.
587 // If a step is not constant, it is pre-calculated before the loop.
588 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
589 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
590 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
591 // Emit calculation of the linear step.
592 CGF.EmitIgnoredExpr(CS);
593 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000594 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000595}
596
597static void emitLinearClauseFinal(CodeGenFunction &CGF,
598 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000599 // Emit the final values of the linear variables.
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000600 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000601 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000602 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000603 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000604 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
605 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000606 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000607 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000608 auto *OrigAddr = CGF.EmitLValue(&DRE).getAddress();
609 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000610 VarScope.addPrivate(OrigVD,
611 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
612 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000613 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000614 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000615 }
616 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000617}
618
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000619static void emitAlignedClause(CodeGenFunction &CGF,
620 const OMPExecutableDirective &D) {
621 for (auto &&I = D.getClausesOfKind(OMPC_aligned); I; ++I) {
622 auto *Clause = cast<OMPAlignedClause>(*I);
623 unsigned ClauseAlignment = 0;
624 if (auto AlignmentExpr = Clause->getAlignment()) {
625 auto AlignmentCI =
626 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
627 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000628 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000629 for (auto E : Clause->varlists()) {
630 unsigned Alignment = ClauseAlignment;
631 if (Alignment == 0) {
632 // OpenMP [2.8.1, Description]
633 // If no optional parameter is specified, implementation-defined default
634 // alignments for SIMD instructions on the target platforms are assumed.
635 Alignment =
636 CGF.CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
637 E->getType());
638 }
639 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
640 "alignment is not power of 2");
641 if (Alignment != 0) {
642 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
643 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
644 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000645 }
646 }
647}
648
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000649static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000650 CodeGenFunction::OMPPrivateScope &LoopScope,
651 ArrayRef<Expr *> Counters) {
652 for (auto *E : Counters) {
653 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000654 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000655 // Emit var without initialization.
656 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
657 CGF.EmitAutoVarCleanups(VarEmission);
658 return VarEmission.getAllocatedAddress();
659 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000660 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000661}
662
Alexey Bataev62dbb972015-04-22 11:59:37 +0000663static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
664 const Expr *Cond, llvm::BasicBlock *TrueBlock,
665 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000666 {
667 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000668 emitPrivateLoopCounters(CGF, PreCondScope, S.counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000669 const VarDecl *IVDecl =
670 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
671 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
672 // Emit var without initialization.
673 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
674 CGF.EmitAutoVarCleanups(VarEmission);
675 return VarEmission.getAllocatedAddress();
676 });
677 assert(IsRegistered && "counter already registered as private");
678 // Silence the warning about unused variable.
679 (void)IsRegistered;
680 (void)PreCondScope.Privatize();
681 // Initialize internal counter to 0 to calculate initial values of real
682 // counters.
683 LValue IV = CGF.EmitLValue(S.getIterationVariable());
684 CGF.EmitStoreOfScalar(
685 llvm::ConstantInt::getNullValue(
686 IV.getAddress()->getType()->getPointerElementType()),
687 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
688 // Get initial values of real counters.
689 for (auto I : S.updates()) {
690 CGF.EmitIgnoredExpr(I);
691 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000692 }
693 // Check that loop is executed at least one time.
694 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
695}
696
Alexander Musman3276a272015-03-21 10:12:56 +0000697static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000698emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000699 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000700 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
701 auto *C = cast<OMPLinearClause>(*I);
702 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000703 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
704 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
705 // Emit var without initialization.
706 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
707 CGF.EmitAutoVarCleanups(VarEmission);
708 return VarEmission.getAllocatedAddress();
709 });
710 assert(IsRegistered && "linear var already registered as private");
711 // Silence the warning about unused variable.
712 (void)IsRegistered;
713 }
714 }
715}
716
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000717static void emitSafelenClause(CodeGenFunction &CGF,
718 const OMPExecutableDirective &D) {
719 if (auto *C =
720 cast_or_null<OMPSafelenClause>(D.getSingleClause(OMPC_safelen))) {
721 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
722 /*ignoreResult=*/true);
723 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
724 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
725 // In presence of finite 'safelen', it may be unsafe to mark all
726 // the memory instructions parallel, because loop-carried
727 // dependences of 'safelen' iterations are possible.
728 CGF.LoopStack.setParallel(false);
729 }
730}
731
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000732void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
733 // Walk clauses and process safelen/lastprivate.
734 LoopStack.setParallel();
735 LoopStack.setVectorizerEnable(true);
736 emitSafelenClause(*this, D);
737}
738
739void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
740 auto IC = D.counters().begin();
741 for (auto F : D.finals()) {
742 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
743 if (LocalDeclMap.lookup(OrigVD)) {
744 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
745 CapturedStmtInfo->lookup(OrigVD) != nullptr,
746 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
747 auto *OrigAddr = EmitLValue(&DRE).getAddress();
748 OMPPrivateScope VarScope(*this);
749 VarScope.addPrivate(OrigVD,
750 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
751 (void)VarScope.Privatize();
752 EmitIgnoredExpr(F);
753 }
754 ++IC;
755 }
756 emitLinearClauseFinal(*this, D);
757}
758
Alexander Musman515ad8c2014-05-22 08:54:05 +0000759void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000760 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000761 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000762 // for (IV in 0..LastIteration) BODY;
763 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000764 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000765 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000766
Alexey Bataev62dbb972015-04-22 11:59:37 +0000767 // Emit: if (PreCond) - begin.
768 // If the condition constant folds and can be elided, avoid emitting the
769 // whole loop.
770 bool CondConstant;
771 llvm::BasicBlock *ContBlock = nullptr;
772 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
773 if (!CondConstant)
774 return;
775 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000776 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
777 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000778 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
779 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000780 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000781 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000782 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000783
784 // Emit the loop iteration variable.
785 const Expr *IVExpr = S.getIterationVariable();
786 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
787 CGF.EmitVarDecl(*IVDecl);
788 CGF.EmitIgnoredExpr(S.getInit());
789
790 // Emit the iterations count variable.
791 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000792 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000793 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
794 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
795 // Emit calculation of the iterations count.
796 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000797 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000799 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000800
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000801 emitAlignedClause(CGF, S);
802 emitLinearClauseInit(CGF, S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000803 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000804 {
805 OMPPrivateScope LoopScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000806 emitPrivateLoopCounters(CGF, LoopScope, S.counters());
807 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000808 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000809 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000810 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000811 (void)LoopScope.Privatize();
812 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
Alexey Bataevae05c292015-06-16 11:59:36 +0000813 S.getCond(), S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000814 [&S](CodeGenFunction &CGF) {
815 CGF.EmitOMPLoopBody(S);
816 CGF.EmitStopPoint(&S);
817 },
818 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000819 // Emit final copy of the lastprivate variables at the end of loops.
820 if (HasLastprivateClause) {
821 CGF.EmitOMPLastprivateClauseFinal(S);
822 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000823 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000824 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000825 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000826 // Emit: if (PreCond) - end.
827 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000828 CGF.EmitBranch(ContBlock);
829 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000830 }
831 };
832 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000833}
834
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000835void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
836 const OMPLoopDirective &S,
837 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000838 bool Ordered, llvm::Value *LB,
839 llvm::Value *UB, llvm::Value *ST,
840 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000841 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000842
843 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000844 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000845
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000846 assert((Ordered ||
847 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000848 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000849
850 // Emit outer loop.
851 //
852 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000853 // When schedule(dynamic,chunk_size) is specified, the iterations are
854 // distributed to threads in the team in chunks as the threads request them.
855 // Each thread executes a chunk of iterations, then requests another chunk,
856 // until no chunks remain to be distributed. Each chunk contains chunk_size
857 // iterations, except for the last chunk to be distributed, which may have
858 // fewer iterations. When no chunk_size is specified, it defaults to 1.
859 //
860 // When schedule(guided,chunk_size) is specified, the iterations are assigned
861 // to threads in the team in chunks as the executing threads request them.
862 // Each thread executes a chunk of iterations, then requests another chunk,
863 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
864 // each chunk is proportional to the number of unassigned iterations divided
865 // by the number of threads in the team, decreasing to 1. For a chunk_size
866 // with value k (greater than 1), the size of each chunk is determined in the
867 // same way, with the restriction that the chunks do not contain fewer than k
868 // iterations (except for the last chunk to be assigned, which may have fewer
869 // than k iterations).
870 //
871 // When schedule(auto) is specified, the decision regarding scheduling is
872 // delegated to the compiler and/or runtime system. The programmer gives the
873 // implementation the freedom to choose any possible mapping of iterations to
874 // threads in the team.
875 //
876 // When schedule(runtime) is specified, the decision regarding scheduling is
877 // deferred until run time, and the schedule and chunk size are taken from the
878 // run-sched-var ICV. If the ICV is set to auto, the schedule is
879 // implementation defined
880 //
881 // while(__kmpc_dispatch_next(&LB, &UB)) {
882 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000883 // while (idx <= UB) { BODY; ++idx;
884 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
885 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000886 // }
887 //
888 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000889 // When schedule(static, chunk_size) is specified, iterations are divided into
890 // chunks of size chunk_size, and the chunks are assigned to the threads in
891 // the team in a round-robin fashion in the order of the thread number.
892 //
893 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
894 // while (idx <= UB) { BODY; ++idx; } // inner loop
895 // LB = LB + ST;
896 // UB = UB + ST;
897 // }
898 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000899
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000900 const Expr *IVExpr = S.getIterationVariable();
901 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
902 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
903
Alexander Musman92bdaab2015-03-12 13:37:50 +0000904 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000905 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
906 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
907 : UB),
908 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000909
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000910 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
911
912 // Start the loop with a block that tests the condition.
913 auto CondBlock = createBasicBlock("omp.dispatch.cond");
914 EmitBlock(CondBlock);
915 LoopStack.push(CondBlock);
916
917 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000918 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000919 // UB = min(UB, GlobalUB)
920 EmitIgnoredExpr(S.getEnsureUpperBound());
921 // IV = LB
922 EmitIgnoredExpr(S.getInit());
923 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +0000924 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +0000925 } else {
926 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
927 IL, LB, UB, ST);
928 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000929
930 // If there are any cleanups between here and the loop-exit scope,
931 // create a block to stage a loop exit along.
932 auto ExitBlock = LoopExit.getBlock();
933 if (LoopScope.requiresCleanups())
934 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
935
936 auto LoopBody = createBasicBlock("omp.dispatch.body");
937 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
938 if (ExitBlock != LoopExit.getBlock()) {
939 EmitBlock(ExitBlock);
940 EmitBranchThroughCleanup(LoopExit);
941 }
942 EmitBlock(LoopBody);
943
Alexander Musman92bdaab2015-03-12 13:37:50 +0000944 // Emit "IV = LB" (in case of static schedule, we have already calculated new
945 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000946 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000947 EmitIgnoredExpr(S.getInit());
948
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000949 // Create a block for the increment.
950 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
951 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
952
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000953 // Generate !llvm.loop.parallel metadata for loads and stores for loops
954 // with dynamic/guided scheduling and without ordered clause.
955 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
956 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
957 ScheduleKind == OMPC_SCHEDULE_guided) &&
958 !Ordered);
959 } else {
960 EmitOMPSimdInit(S);
961 }
962
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000963 SourceLocation Loc = S.getLocStart();
964 EmitOMPInnerLoop(
Alexey Bataevae05c292015-06-16 11:59:36 +0000965 S, LoopScope.requiresCleanups(), S.getCond(),
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000966 S.getInc(),
967 [&S](CodeGenFunction &CGF) {
968 CGF.EmitOMPLoopBody(S);
969 CGF.EmitStopPoint(&S);
970 },
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000971 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
972 if (Ordered) {
973 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000974 CGF, Loc, IVSize, IVSigned);
975 }
976 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000977
978 EmitBlock(Continue.getBlock());
979 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000980 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000981 // Emit "LB = LB + Stride", "UB = UB + Stride".
982 EmitIgnoredExpr(S.getNextLowerBound());
983 EmitIgnoredExpr(S.getNextUpperBound());
984 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000985
986 EmitBranch(CondBlock);
987 LoopStack.pop();
988 // Emit the fall-through block.
989 EmitBlock(LoopExit.getBlock());
990
991 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000992 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000993 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000994}
995
Alexander Musmanc6388682014-12-15 07:07:06 +0000996/// \brief Emit a helper variable and return corresponding lvalue.
997static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
998 const DeclRefExpr *Helper) {
999 auto VDecl = cast<VarDecl>(Helper->getDecl());
1000 CGF.EmitVarDecl(*VDecl);
1001 return CGF.EmitLValue(Helper);
1002}
1003
Alexey Bataev040d5402015-05-12 08:35:28 +00001004static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1005emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1006 bool OuterRegion) {
1007 // Detect the loop schedule kind and chunk.
1008 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1009 llvm::Value *Chunk = nullptr;
1010 if (auto *C =
1011 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
1012 ScheduleKind = C->getScheduleKind();
1013 if (const auto *Ch = C->getChunkSize()) {
1014 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1015 if (OuterRegion) {
1016 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1017 CGF.EmitVarDecl(*ImpVar);
1018 CGF.EmitStoreThroughLValue(
1019 CGF.EmitAnyExpr(Ch),
1020 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1021 ImpVar->getType()));
1022 } else {
1023 Ch = ImpRef;
1024 }
1025 }
1026 if (!C->getHelperChunkSize() || !OuterRegion) {
1027 Chunk = CGF.EmitScalarExpr(Ch);
1028 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
1029 S.getIterationVariable()->getType());
1030 }
1031 }
1032 }
1033 return std::make_pair(Chunk, ScheduleKind);
1034}
1035
Alexey Bataev38e89532015-04-16 04:54:05 +00001036bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001037 // Emit the loop iteration variable.
1038 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1039 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1040 EmitVarDecl(*IVDecl);
1041
1042 // Emit the iterations count variable.
1043 // If it is not a variable, Sema decided to calculate iterations count on each
1044 // iteration (e.g., it is foldable into a constant).
1045 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1046 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1047 // Emit calculation of the iterations count.
1048 EmitIgnoredExpr(S.getCalcLastIteration());
1049 }
1050
1051 auto &RT = CGM.getOpenMPRuntime();
1052
Alexey Bataev38e89532015-04-16 04:54:05 +00001053 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001054 // Check pre-condition.
1055 {
1056 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001057 // If the condition constant folds and can be elided, avoid emitting the
1058 // whole loop.
1059 bool CondConstant;
1060 llvm::BasicBlock *ContBlock = nullptr;
1061 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1062 if (!CondConstant)
1063 return false;
1064 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001065 auto *ThenBlock = createBasicBlock("omp.precond.then");
1066 ContBlock = createBasicBlock("omp.precond.end");
1067 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001068 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001069 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001070 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001071 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001072
1073 emitAlignedClause(*this, S);
1074 emitLinearClauseInit(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001075 // Emit 'then' code.
1076 {
1077 // Emit helper vars inits.
1078 LValue LB =
1079 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1080 LValue UB =
1081 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1082 LValue ST =
1083 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1084 LValue IL =
1085 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1086
1087 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001088 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1089 // Emit implicit barrier to synchronize threads and avoid data races on
1090 // initialization of firstprivate variables.
1091 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1092 OMPD_unknown);
1093 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001094 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001095 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001096 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001097 emitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001098 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001099 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001100
1101 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001102 llvm::Value *Chunk;
1103 OpenMPScheduleClauseKind ScheduleKind;
1104 auto ScheduleInfo =
1105 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1106 Chunk = ScheduleInfo.first;
1107 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001108 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1109 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001110 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001111 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001112 /* Chunked */ Chunk != nullptr) &&
1113 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001114 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1115 EmitOMPSimdInit(S);
1116 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001117 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1118 // When no chunk_size is specified, the iteration space is divided into
1119 // chunks that are approximately equal in size, and at most one chunk is
1120 // distributed to each thread. Note that the size of the chunks is
1121 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001122 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001123 Ordered, IL.getAddress(), LB.getAddress(),
1124 UB.getAddress(), ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001125 // UB = min(UB, GlobalUB);
1126 EmitIgnoredExpr(S.getEnsureUpperBound());
1127 // IV = LB;
1128 EmitIgnoredExpr(S.getInit());
1129 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001130 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1131 S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001132 [&S](CodeGenFunction &CGF) {
1133 CGF.EmitOMPLoopBody(S);
1134 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001135 },
1136 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001137 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001138 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001139 } else {
1140 // Emit the outer loop, which requests its work chunk [LB..UB] from
1141 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001142 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1143 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1144 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001145 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001146 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001147 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1148 if (HasLastprivateClause)
1149 EmitOMPLastprivateClauseFinal(
1150 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001151 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001152 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1153 EmitOMPSimdFinal(S);
1154 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001155 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001156 if (ContBlock) {
1157 EmitBranch(ContBlock);
1158 EmitBlock(ContBlock, true);
1159 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001160 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001161 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001162}
1163
1164void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001165 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001166 bool HasLastprivates = false;
1167 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1168 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1169 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001171
1172 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001173 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001174 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1175 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001176}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001177
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001178void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1179 LexicalScope Scope(*this, S.getSourceRange());
1180 bool HasLastprivates = false;
1181 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1182 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1183 };
1184 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
1185
1186 // Emit an implicit barrier at the end.
1187 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
1188 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1189 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001190}
1191
Alexey Bataev2df54a02015-03-12 08:53:29 +00001192static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1193 const Twine &Name,
1194 llvm::Value *Init = nullptr) {
1195 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1196 if (Init)
1197 CGF.EmitScalarInit(Init, LVal);
1198 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001199}
1200
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001201static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1202 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001203 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1204 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1205 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001206 bool HasLastprivates = false;
1207 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001208 auto &C = CGF.CGM.getContext();
1209 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1210 // Emit helper vars inits.
1211 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1212 CGF.Builder.getInt32(0));
1213 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1214 LValue UB =
1215 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1216 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1217 CGF.Builder.getInt32(1));
1218 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1219 CGF.Builder.getInt32(0));
1220 // Loop counter.
1221 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1222 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001223 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001224 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001225 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001226 // Generate condition for loop.
1227 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1228 OK_Ordinary, S.getLocStart(),
1229 /*fpContractable=*/false);
1230 // Increment for loop counter.
1231 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1232 OK_Ordinary, S.getLocStart());
1233 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1234 // Iterate through all sections and emit a switch construct:
1235 // switch (IV) {
1236 // case 0:
1237 // <SectionStmt[0]>;
1238 // break;
1239 // ...
1240 // case <NumSection> - 1:
1241 // <SectionStmt[<NumSection> - 1]>;
1242 // break;
1243 // }
1244 // .omp.sections.exit:
1245 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1246 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1247 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1248 CS->size());
1249 unsigned CaseNumber = 0;
1250 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1251 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1252 CGF.EmitBlock(CaseBB);
1253 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1254 CGF.EmitStmt(*C);
1255 CGF.EmitBranch(ExitBB);
1256 }
1257 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1258 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001259
1260 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1261 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1262 // Emit implicit barrier to synchronize threads and avoid data races on
1263 // initialization of firstprivate variables.
1264 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1265 OMPD_unknown);
1266 }
Alexey Bataev73870832015-04-27 04:12:12 +00001267 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001268 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001269 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001270 (void)LoopScope.Privatize();
1271
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272 // Emit static non-chunked loop.
1273 CGF.CGM.getOpenMPRuntime().emitForInit(
1274 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001275 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1276 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001277 // UB = min(UB, GlobalUB);
1278 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1279 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1280 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1281 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1282 // IV = LB;
1283 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1284 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001285 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1286 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001287 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001288 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001289 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001290
1291 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1292 if (HasLastprivates)
1293 CGF.EmitOMPLastprivateClauseFinal(
1294 S, CGF.Builder.CreateIsNotNull(
1295 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001296 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001297
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001298 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001299 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1300 // clause. Otherwise the barrier will be generated by the codegen for the
1301 // directive.
1302 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1303 // Emit implicit barrier to synchronize threads and avoid data races on
1304 // initialization of firstprivate variables.
1305 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1306 OMPD_unknown);
1307 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001308 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001309 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001310 // If only one section is found - no need to generate loop, emit as a single
1311 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001312 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001313 // No need to generate reductions for sections with single section region, we
1314 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001315 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001316 // No need to generate lastprivates for sections with single section region,
1317 // we can use original shared variable for all calculations with barrier at
1318 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001319 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001320 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1321 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1322 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001323 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001324 (void)SingleScope.Privatize();
1325
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001326 CGF.EmitStmt(Stmt);
1327 CGF.EnsureInsertPoint();
1328 };
1329 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1330 llvm::None, llvm::None,
1331 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001332 // Emit barrier for firstprivates, lastprivates or reductions only if
1333 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1334 // generated by the codegen for the directive.
1335 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1336 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001337 // Emit implicit barrier to synchronize threads and avoid data races on
1338 // initialization of firstprivate variables.
1339 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1340 OMPD_unknown);
1341 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001342 return OMPD_single;
1343}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001344
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001345void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1346 LexicalScope Scope(*this, S.getSourceRange());
1347 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001348 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001349 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001350 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001351 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001352}
1353
1354void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001355 LexicalScope Scope(*this, S.getSourceRange());
1356 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1357 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1358 CGF.EnsureInsertPoint();
1359 };
1360 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001361}
1362
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001363void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001364 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001365 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001366 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001367 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001368 // Check if there are any 'copyprivate' clauses associated with this
1369 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001370 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001371 // Build a list of copyprivate variables along with helper expressions
1372 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001373 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001374 auto *C = cast<OMPCopyprivateClause>(*I);
1375 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001376 DestExprs.append(C->destination_exprs().begin(),
1377 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001378 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001379 AssignmentOps.append(C->assignment_ops().begin(),
1380 C->assignment_ops().end());
1381 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001382 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001383 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001384 bool HasFirstprivates;
1385 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1386 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1387 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001388 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001389 (void)SingleScope.Privatize();
1390
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001391 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1392 CGF.EnsureInsertPoint();
1393 };
1394 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001395 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001396 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001397 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1398 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1399 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1400 CopyprivateVars.empty()) {
1401 CGM.getOpenMPRuntime().emitBarrierCall(
1402 *this, S.getLocStart(),
1403 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001404 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001405}
1406
Alexey Bataev8d690652014-12-04 07:23:53 +00001407void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001408 LexicalScope Scope(*this, S.getSourceRange());
1409 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1410 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1411 CGF.EnsureInsertPoint();
1412 };
1413 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001414}
1415
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001416void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001417 LexicalScope Scope(*this, S.getSourceRange());
1418 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1419 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1420 CGF.EnsureInsertPoint();
1421 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001422 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001423 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001424}
1425
Alexey Bataev671605e2015-04-13 05:28:11 +00001426void CodeGenFunction::EmitOMPParallelForDirective(
1427 const OMPParallelForDirective &S) {
1428 // Emit directive as a combined directive that consists of two implicit
1429 // directives: 'parallel' with 'for' directive.
1430 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001431 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001432 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1433 CGF.EmitOMPWorksharingLoop(S);
1434 // Emit implicit barrier at the end of parallel region, but this barrier
1435 // is at the end of 'for' directive, so emit it as the implicit barrier for
1436 // this 'for' directive.
1437 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1438 OMPD_parallel);
1439 };
1440 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001441}
1442
Alexander Musmane4e893b2014-09-23 09:33:00 +00001443void CodeGenFunction::EmitOMPParallelForSimdDirective(
1444 const OMPParallelForSimdDirective &) {
1445 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1446}
1447
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001448void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001449 const OMPParallelSectionsDirective &S) {
1450 // Emit directive as a combined directive that consists of two implicit
1451 // directives: 'parallel' with 'sections' directive.
1452 LexicalScope Scope(*this, S.getSourceRange());
1453 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1454 (void)emitSections(CGF, S);
1455 // Emit implicit barrier at the end of parallel region.
1456 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1457 OMPD_parallel);
1458 };
1459 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001460}
1461
Alexey Bataev62b63b12015-03-10 07:28:44 +00001462void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1463 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001464 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001465 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1466 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1467 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001468 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001469 // The first function argument for tasks is a thread id, the second one is a
1470 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001471 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1472 // Get list of private variables.
1473 llvm::SmallVector<const Expr *, 8> PrivateVars;
1474 llvm::SmallVector<const Expr *, 8> PrivateCopies;
1475 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1476 auto *C = cast<OMPPrivateClause>(*I);
1477 auto IRef = C->varlist_begin();
1478 for (auto *IInit : C->private_copies()) {
1479 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1480 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1481 PrivateVars.push_back(*IRef);
1482 PrivateCopies.push_back(IInit);
1483 }
1484 ++IRef;
1485 }
1486 }
1487 EmittedAsPrivate.clear();
1488 // Get list of firstprivate variables.
1489 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1490 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1491 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1492 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1493 auto *C = cast<OMPFirstprivateClause>(*I);
1494 auto IRef = C->varlist_begin();
1495 auto IElemInitRef = C->inits().begin();
1496 for (auto *IInit : C->private_copies()) {
1497 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1498 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1499 FirstprivateVars.push_back(*IRef);
1500 FirstprivateCopies.push_back(IInit);
1501 FirstprivateInits.push_back(*IElemInitRef);
1502 }
1503 ++IRef, ++IElemInitRef;
1504 }
1505 }
1506 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1507 CodeGenFunction &CGF) {
1508 // Set proper addresses for generated private copies.
1509 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1510 OMPPrivateScope Scope(CGF);
1511 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
1512 auto *CopyFn = CGF.Builder.CreateAlignedLoad(
1513 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)),
1514 CGF.PointerAlignInBytes);
1515 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad(
1516 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)),
1517 CGF.PointerAlignInBytes);
1518 // Map privates.
1519 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16>
1520 PrivatePtrs;
1521 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1522 CallArgs.push_back(PrivatesPtr);
1523 for (auto *E : PrivateVars) {
1524 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1525 auto *PrivatePtr =
1526 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1527 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1528 CallArgs.push_back(PrivatePtr);
1529 }
1530 for (auto *E : FirstprivateVars) {
1531 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1532 auto *PrivatePtr =
1533 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1534 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1535 CallArgs.push_back(PrivatePtr);
1536 }
1537 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1538 for (auto &&Pair : PrivatePtrs) {
1539 auto *Replacement =
1540 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes);
1541 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1542 }
1543 }
1544 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001545 if (*PartId) {
1546 // TODO: emit code for untied tasks.
1547 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001548 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001549 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001550 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001551 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001552 // Check if we should emit tied or untied task.
1553 bool Tied = !S.getSingleClause(OMPC_untied);
1554 // Check if the task is final
1555 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1556 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1557 // If the condition constant folds and can be elided, try to avoid emitting
1558 // the condition and the dead arm of the if/else.
1559 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1560 bool CondConstant;
1561 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1562 Final.setInt(CondConstant);
1563 else
1564 Final.setPointer(EvaluateExprAsBool(Cond));
1565 } else {
1566 // By default the task is not final.
1567 Final.setInt(/*IntVal=*/false);
1568 }
1569 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001570 const Expr *IfCond = nullptr;
1571 if (auto C = S.getSingleClause(OMPC_if)) {
1572 IfCond = cast<OMPIfClause>(C)->getCondition();
1573 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001574 CGM.getOpenMPRuntime().emitTaskCall(
1575 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001576 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev9e034042015-05-05 04:05:12 +00001577 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001578}
1579
Alexey Bataev9f797f32015-02-05 05:57:51 +00001580void CodeGenFunction::EmitOMPTaskyieldDirective(
1581 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001582 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001583}
1584
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001585void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001586 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001587}
1588
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001589void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1590 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001591}
1592
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001593void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001594 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1595 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1596 auto FlushClause = cast<OMPFlushClause>(C);
1597 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1598 FlushClause->varlist_end());
1599 }
1600 return llvm::None;
1601 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001602}
1603
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001604void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1605 LexicalScope Scope(*this, S.getSourceRange());
1606 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1607 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1608 CGF.EnsureInsertPoint();
1609 };
1610 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001611}
1612
Alexey Bataevb57056f2015-01-22 06:17:56 +00001613static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1614 QualType SrcType, QualType DestType) {
1615 assert(CGF.hasScalarEvaluationKind(DestType) &&
1616 "DestType must have scalar evaluation kind.");
1617 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1618 return Val.isScalar()
1619 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1620 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1621 DestType);
1622}
1623
1624static CodeGenFunction::ComplexPairTy
1625convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1626 QualType DestType) {
1627 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1628 "DestType must have complex evaluation kind.");
1629 CodeGenFunction::ComplexPairTy ComplexVal;
1630 if (Val.isScalar()) {
1631 // Convert the input element to the element type of the complex.
1632 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1633 auto ScalarVal =
1634 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1635 ComplexVal = CodeGenFunction::ComplexPairTy(
1636 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1637 } else {
1638 assert(Val.isComplex() && "Must be a scalar or complex.");
1639 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1640 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1641 ComplexVal.first = CGF.EmitScalarConversion(
1642 Val.getComplexVal().first, SrcElementType, DestElementType);
1643 ComplexVal.second = CGF.EmitScalarConversion(
1644 Val.getComplexVal().second, SrcElementType, DestElementType);
1645 }
1646 return ComplexVal;
1647}
1648
Alexey Bataev5e018f92015-04-23 06:35:10 +00001649static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1650 LValue LVal, RValue RVal) {
1651 if (LVal.isGlobalReg()) {
1652 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1653 } else {
1654 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1655 : llvm::Monotonic,
1656 LVal.isVolatile(), /*IsInit=*/false);
1657 }
1658}
1659
1660static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1661 QualType RValTy) {
1662 switch (CGF.getEvaluationKind(LVal.getType())) {
1663 case TEK_Scalar:
1664 CGF.EmitStoreThroughLValue(
1665 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1666 LVal);
1667 break;
1668 case TEK_Complex:
1669 CGF.EmitStoreOfComplex(
1670 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1671 /*isInit=*/false);
1672 break;
1673 case TEK_Aggregate:
1674 llvm_unreachable("Must be a scalar or complex.");
1675 }
1676}
1677
Alexey Bataevb57056f2015-01-22 06:17:56 +00001678static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1679 const Expr *X, const Expr *V,
1680 SourceLocation Loc) {
1681 // v = x;
1682 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1683 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1684 LValue XLValue = CGF.EmitLValue(X);
1685 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001686 RValue Res = XLValue.isGlobalReg()
1687 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1688 : CGF.EmitAtomicLoad(XLValue, Loc,
1689 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001690 : llvm::Monotonic,
1691 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001692 // OpenMP, 2.12.6, atomic Construct
1693 // Any atomic construct with a seq_cst clause forces the atomically
1694 // performed operation to include an implicit flush operation without a
1695 // list.
1696 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001697 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001698 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001699}
1700
Alexey Bataevb8329262015-02-27 06:33:30 +00001701static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1702 const Expr *X, const Expr *E,
1703 SourceLocation Loc) {
1704 // x = expr;
1705 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001706 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001707 // OpenMP, 2.12.6, atomic Construct
1708 // Any atomic construct with a seq_cst clause forces the atomically
1709 // performed operation to include an implicit flush operation without a
1710 // list.
1711 if (IsSeqCst)
1712 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1713}
1714
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001715static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1716 RValue Update,
1717 BinaryOperatorKind BO,
1718 llvm::AtomicOrdering AO,
1719 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001720 auto &Context = CGF.CGM.getContext();
1721 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001722 // expression is simple and atomic is allowed for the given type for the
1723 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001724 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001725 !Update.getScalarVal()->getType()->isIntegerTy() ||
1726 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1727 (Update.getScalarVal()->getType() !=
1728 X.getAddress()->getType()->getPointerElementType())) ||
1729 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001730 !Context.getTargetInfo().hasBuiltinAtomic(
1731 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001732 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001733
1734 llvm::AtomicRMWInst::BinOp RMWOp;
1735 switch (BO) {
1736 case BO_Add:
1737 RMWOp = llvm::AtomicRMWInst::Add;
1738 break;
1739 case BO_Sub:
1740 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001741 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001742 RMWOp = llvm::AtomicRMWInst::Sub;
1743 break;
1744 case BO_And:
1745 RMWOp = llvm::AtomicRMWInst::And;
1746 break;
1747 case BO_Or:
1748 RMWOp = llvm::AtomicRMWInst::Or;
1749 break;
1750 case BO_Xor:
1751 RMWOp = llvm::AtomicRMWInst::Xor;
1752 break;
1753 case BO_LT:
1754 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1755 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1756 : llvm::AtomicRMWInst::Max)
1757 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1758 : llvm::AtomicRMWInst::UMax);
1759 break;
1760 case BO_GT:
1761 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1762 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1763 : llvm::AtomicRMWInst::Min)
1764 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1765 : llvm::AtomicRMWInst::UMin);
1766 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001767 case BO_Assign:
1768 RMWOp = llvm::AtomicRMWInst::Xchg;
1769 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001770 case BO_Mul:
1771 case BO_Div:
1772 case BO_Rem:
1773 case BO_Shl:
1774 case BO_Shr:
1775 case BO_LAnd:
1776 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001777 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001778 case BO_PtrMemD:
1779 case BO_PtrMemI:
1780 case BO_LE:
1781 case BO_GE:
1782 case BO_EQ:
1783 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001784 case BO_AddAssign:
1785 case BO_SubAssign:
1786 case BO_AndAssign:
1787 case BO_OrAssign:
1788 case BO_XorAssign:
1789 case BO_MulAssign:
1790 case BO_DivAssign:
1791 case BO_RemAssign:
1792 case BO_ShlAssign:
1793 case BO_ShrAssign:
1794 case BO_Comma:
1795 llvm_unreachable("Unsupported atomic update operation");
1796 }
1797 auto *UpdateVal = Update.getScalarVal();
1798 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1799 UpdateVal = CGF.Builder.CreateIntCast(
1800 IC, X.getAddress()->getType()->getPointerElementType(),
1801 X.getType()->hasSignedIntegerRepresentation());
1802 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001803 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1804 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001805}
1806
Alexey Bataev5e018f92015-04-23 06:35:10 +00001807std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001808 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1809 llvm::AtomicOrdering AO, SourceLocation Loc,
1810 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1811 // Update expressions are allowed to have the following forms:
1812 // x binop= expr; -> xrval + expr;
1813 // x++, ++x -> xrval + 1;
1814 // x--, --x -> xrval - 1;
1815 // x = x binop expr; -> xrval binop expr
1816 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001817 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1818 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001819 if (X.isGlobalReg()) {
1820 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1821 // 'xrval'.
1822 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1823 } else {
1824 // Perform compare-and-swap procedure.
1825 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001826 }
1827 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001828 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001829}
1830
1831static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1832 const Expr *X, const Expr *E,
1833 const Expr *UE, bool IsXLHSInRHSPart,
1834 SourceLocation Loc) {
1835 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1836 "Update expr in 'atomic update' must be a binary operator.");
1837 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1838 // Update expressions are allowed to have the following forms:
1839 // x binop= expr; -> xrval + expr;
1840 // x++, ++x -> xrval + 1;
1841 // x--, --x -> xrval - 1;
1842 // x = x binop expr; -> xrval binop expr
1843 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001844 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001845 LValue XLValue = CGF.EmitLValue(X);
1846 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001847 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001848 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1849 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1850 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1851 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1852 auto Gen =
1853 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1854 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1855 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1856 return CGF.EmitAnyExpr(UE);
1857 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001858 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1859 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1860 // OpenMP, 2.12.6, atomic Construct
1861 // Any atomic construct with a seq_cst clause forces the atomically
1862 // performed operation to include an implicit flush operation without a
1863 // list.
1864 if (IsSeqCst)
1865 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1866}
1867
1868static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1869 QualType SourceType, QualType ResType) {
1870 switch (CGF.getEvaluationKind(ResType)) {
1871 case TEK_Scalar:
1872 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1873 case TEK_Complex: {
1874 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1875 return RValue::getComplex(Res.first, Res.second);
1876 }
1877 case TEK_Aggregate:
1878 break;
1879 }
1880 llvm_unreachable("Must be a scalar or complex.");
1881}
1882
1883static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1884 bool IsPostfixUpdate, const Expr *V,
1885 const Expr *X, const Expr *E,
1886 const Expr *UE, bool IsXLHSInRHSPart,
1887 SourceLocation Loc) {
1888 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1889 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1890 RValue NewVVal;
1891 LValue VLValue = CGF.EmitLValue(V);
1892 LValue XLValue = CGF.EmitLValue(X);
1893 RValue ExprRValue = CGF.EmitAnyExpr(E);
1894 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1895 QualType NewVValType;
1896 if (UE) {
1897 // 'x' is updated with some additional value.
1898 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1899 "Update expr in 'atomic capture' must be a binary operator.");
1900 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1901 // Update expressions are allowed to have the following forms:
1902 // x binop= expr; -> xrval + expr;
1903 // x++, ++x -> xrval + 1;
1904 // x--, --x -> xrval - 1;
1905 // x = x binop expr; -> xrval binop expr
1906 // x = expr Op x; - > expr binop xrval;
1907 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1908 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1909 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1910 NewVValType = XRValExpr->getType();
1911 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1912 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1913 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1914 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1915 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1916 RValue Res = CGF.EmitAnyExpr(UE);
1917 NewVVal = IsPostfixUpdate ? XRValue : Res;
1918 return Res;
1919 };
1920 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1921 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1922 if (Res.first) {
1923 // 'atomicrmw' instruction was generated.
1924 if (IsPostfixUpdate) {
1925 // Use old value from 'atomicrmw'.
1926 NewVVal = Res.second;
1927 } else {
1928 // 'atomicrmw' does not provide new value, so evaluate it using old
1929 // value of 'x'.
1930 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1931 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1932 NewVVal = CGF.EmitAnyExpr(UE);
1933 }
1934 }
1935 } else {
1936 // 'x' is simply rewritten with some 'expr'.
1937 NewVValType = X->getType().getNonReferenceType();
1938 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1939 X->getType().getNonReferenceType());
1940 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1941 NewVVal = XRValue;
1942 return ExprRValue;
1943 };
1944 // Try to perform atomicrmw xchg, otherwise simple exchange.
1945 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1946 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1947 Loc, Gen);
1948 if (Res.first) {
1949 // 'atomicrmw' instruction was generated.
1950 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1951 }
1952 }
1953 // Emit post-update store to 'v' of old/new 'x' value.
1954 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001955 // OpenMP, 2.12.6, atomic Construct
1956 // Any atomic construct with a seq_cst clause forces the atomically
1957 // performed operation to include an implicit flush operation without a
1958 // list.
1959 if (IsSeqCst)
1960 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1961}
1962
Alexey Bataevb57056f2015-01-22 06:17:56 +00001963static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001964 bool IsSeqCst, bool IsPostfixUpdate,
1965 const Expr *X, const Expr *V, const Expr *E,
1966 const Expr *UE, bool IsXLHSInRHSPart,
1967 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001968 switch (Kind) {
1969 case OMPC_read:
1970 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1971 break;
1972 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001973 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1974 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001975 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001976 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001977 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1978 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001979 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001980 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1981 IsXLHSInRHSPart, Loc);
1982 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001983 case OMPC_if:
1984 case OMPC_final:
1985 case OMPC_num_threads:
1986 case OMPC_private:
1987 case OMPC_firstprivate:
1988 case OMPC_lastprivate:
1989 case OMPC_reduction:
1990 case OMPC_safelen:
1991 case OMPC_collapse:
1992 case OMPC_default:
1993 case OMPC_seq_cst:
1994 case OMPC_shared:
1995 case OMPC_linear:
1996 case OMPC_aligned:
1997 case OMPC_copyin:
1998 case OMPC_copyprivate:
1999 case OMPC_flush:
2000 case OMPC_proc_bind:
2001 case OMPC_schedule:
2002 case OMPC_ordered:
2003 case OMPC_nowait:
2004 case OMPC_untied:
2005 case OMPC_threadprivate:
2006 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002007 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2008 }
2009}
2010
2011void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
2012 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
2013 OpenMPClauseKind Kind = OMPC_unknown;
2014 for (auto *C : S.clauses()) {
2015 // Find first clause (skip seq_cst clause, if it is first).
2016 if (C->getClauseKind() != OMPC_seq_cst) {
2017 Kind = C->getClauseKind();
2018 break;
2019 }
2020 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002021
2022 const auto *CS =
2023 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002024 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002025 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002026 }
2027 // Processing for statements under 'atomic capture'.
2028 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2029 for (const auto *C : Compound->body()) {
2030 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2031 enterFullExpression(EWC);
2032 }
2033 }
2034 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002035
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002036 LexicalScope Scope(*this, S.getSourceRange());
2037 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002038 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2039 S.getV(), S.getExpr(), S.getUpdateExpr(),
2040 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002041 };
2042 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002043}
2044
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002045void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2046 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2047}
2048
Alexey Bataev13314bf2014-10-09 04:18:56 +00002049void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2050 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2051}