blob: 8666b46498477a619ce63cbc109056054ce14823 [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 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000467 if (auto *C = S.getSingleClause(OMPC_proc_bind)) {
468 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
469 auto *ProcBindClause = cast<OMPProcBindClause>(C);
470 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
471 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
472 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000473 const Expr *IfCond = nullptr;
474 if (auto C = S.getSingleClause(OMPC_if)) {
475 IfCond = cast<OMPIfClause>(C)->getCondition();
476 }
477 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
478 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000479}
480
481void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
482 LexicalScope Scope(*this, S.getSourceRange());
483 // Emit parallel region as a standalone region.
484 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
485 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000486 bool Copyins = CGF.EmitOMPCopyinClause(S);
487 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
488 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000489 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000490 // initialization of firstprivate variables or propagation master's thread
491 // values of threadprivate variables to local instances of that variables
492 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000493 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
494 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000495 }
496 CGF.EmitOMPPrivateClause(S, PrivateScope);
497 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
498 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000499 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000500 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000501 // Emit implicit barrier at the end of the 'parallel' directive.
502 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
503 OMPD_unknown);
504 };
505 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000506}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000507
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000508void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000509 RunCleanupsScope BodyScope(*this);
510 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000511 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000512 EmitIgnoredExpr(I);
513 }
Alexander Musman3276a272015-03-21 10:12:56 +0000514 // Update the linear variables.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000515 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000516 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000517 for (auto U : C->updates()) {
518 EmitIgnoredExpr(U);
519 }
520 }
521
Alexander Musmana5f070a2014-10-01 06:03:56 +0000522 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000523 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000524 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
525 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000526 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000527 // The end (updates/cleanups).
528 EmitBlock(Continue.getBlock());
529 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000530 // TODO: Update lastprivates if the SeparateIter flag is true.
531 // This will be implemented in a follow-up OMPLastprivateClause patch, but
532 // result should be still correct without it, as we do not make these
533 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000534}
535
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000536void CodeGenFunction::EmitOMPInnerLoop(
537 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
538 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000539 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
540 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000541 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000542
543 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000544 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000545 EmitBlock(CondBlock);
546 LoopStack.push(CondBlock);
547
548 // If there are any cleanups between here and the loop-exit scope,
549 // create a block to stage a loop exit along.
550 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000551 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000552 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000553
Alexander Musmand196ef22014-10-07 08:57:09 +0000554 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000555
Alexey Bataev2df54a02015-03-12 08:53:29 +0000556 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000557 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000558 if (ExitBlock != LoopExit.getBlock()) {
559 EmitBlock(ExitBlock);
560 EmitBranchThroughCleanup(LoopExit);
561 }
562
563 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000564 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000565
566 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000567 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000568 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
569
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000570 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000571
572 // Emit "IV = IV + 1" and a back-edge to the condition block.
573 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000574 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000575 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000576 BreakContinueStack.pop_back();
577 EmitBranch(CondBlock);
578 LoopStack.pop();
579 // Emit the fall-through block.
580 EmitBlock(LoopExit.getBlock());
581}
582
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000583void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000584 // Emit inits for the linear variables.
585 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
586 auto *C = cast<OMPLinearClause>(*I);
587 for (auto Init : C->inits()) {
588 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000589 auto *OrigVD = cast<VarDecl>(
590 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
591 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
592 CapturedStmtInfo->lookup(OrigVD) != nullptr,
593 VD->getInit()->getType(), VK_LValue,
594 VD->getInit()->getExprLoc());
595 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
596 EmitExprAsInit(&DRE, VD,
597 MakeAddrLValue(Emission.getAllocatedAddress(),
598 VD->getType(), Emission.Alignment),
599 /*capturedByInit=*/false);
600 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000601 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000602 // Emit the linear steps for the linear clauses.
603 // If a step is not constant, it is pre-calculated before the loop.
604 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
605 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000606 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000607 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000608 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000609 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000610 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000611}
612
613static void emitLinearClauseFinal(CodeGenFunction &CGF,
614 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000615 // Emit the final values of the linear variables.
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000616 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000617 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000618 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000619 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000620 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
621 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000622 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000624 auto *OrigAddr = CGF.EmitLValue(&DRE).getAddress();
625 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 VarScope.addPrivate(OrigVD,
627 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
628 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000629 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000630 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000631 }
632 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000633}
634
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000635static void emitAlignedClause(CodeGenFunction &CGF,
636 const OMPExecutableDirective &D) {
637 for (auto &&I = D.getClausesOfKind(OMPC_aligned); I; ++I) {
638 auto *Clause = cast<OMPAlignedClause>(*I);
639 unsigned ClauseAlignment = 0;
640 if (auto AlignmentExpr = Clause->getAlignment()) {
641 auto AlignmentCI =
642 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
643 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000644 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000645 for (auto E : Clause->varlists()) {
646 unsigned Alignment = ClauseAlignment;
647 if (Alignment == 0) {
648 // OpenMP [2.8.1, Description]
649 // If no optional parameter is specified, implementation-defined default
650 // alignments for SIMD instructions on the target platforms are assumed.
651 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000652 CGF.getContext()
653 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
654 E->getType()->getPointeeType()))
655 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000656 }
657 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
658 "alignment is not power of 2");
659 if (Alignment != 0) {
660 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
661 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
662 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000663 }
664 }
665}
666
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000667static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000668 CodeGenFunction::OMPPrivateScope &LoopScope,
669 ArrayRef<Expr *> Counters) {
670 for (auto *E : Counters) {
671 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000672 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000673 // Emit var without initialization.
674 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
675 CGF.EmitAutoVarCleanups(VarEmission);
676 return VarEmission.getAllocatedAddress();
677 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000678 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000679}
680
Alexey Bataev62dbb972015-04-22 11:59:37 +0000681static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
682 const Expr *Cond, llvm::BasicBlock *TrueBlock,
683 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000684 {
685 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000686 emitPrivateLoopCounters(CGF, PreCondScope, S.counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000687 const VarDecl *IVDecl =
688 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
689 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
690 // Emit var without initialization.
691 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
692 CGF.EmitAutoVarCleanups(VarEmission);
693 return VarEmission.getAllocatedAddress();
694 });
695 assert(IsRegistered && "counter already registered as private");
696 // Silence the warning about unused variable.
697 (void)IsRegistered;
698 (void)PreCondScope.Privatize();
699 // Initialize internal counter to 0 to calculate initial values of real
700 // counters.
701 LValue IV = CGF.EmitLValue(S.getIterationVariable());
702 CGF.EmitStoreOfScalar(
703 llvm::ConstantInt::getNullValue(
704 IV.getAddress()->getType()->getPointerElementType()),
705 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
706 // Get initial values of real counters.
707 for (auto I : S.updates()) {
708 CGF.EmitIgnoredExpr(I);
709 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000710 }
711 // Check that loop is executed at least one time.
712 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
713}
714
Alexander Musman3276a272015-03-21 10:12:56 +0000715static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000716emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000717 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000718 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
719 auto *C = cast<OMPLinearClause>(*I);
720 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000721 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
722 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
723 // Emit var without initialization.
724 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
725 CGF.EmitAutoVarCleanups(VarEmission);
726 return VarEmission.getAllocatedAddress();
727 });
728 assert(IsRegistered && "linear var already registered as private");
729 // Silence the warning about unused variable.
730 (void)IsRegistered;
731 }
732 }
733}
734
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000735static void emitSafelenClause(CodeGenFunction &CGF,
736 const OMPExecutableDirective &D) {
737 if (auto *C =
738 cast_or_null<OMPSafelenClause>(D.getSingleClause(OMPC_safelen))) {
739 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
740 /*ignoreResult=*/true);
741 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
742 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
743 // In presence of finite 'safelen', it may be unsafe to mark all
744 // the memory instructions parallel, because loop-carried
745 // dependences of 'safelen' iterations are possible.
746 CGF.LoopStack.setParallel(false);
747 }
748}
749
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000750void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
751 // Walk clauses and process safelen/lastprivate.
752 LoopStack.setParallel();
753 LoopStack.setVectorizerEnable(true);
754 emitSafelenClause(*this, D);
755}
756
757void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
758 auto IC = D.counters().begin();
759 for (auto F : D.finals()) {
760 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000761 if (LocalDeclMap.lookup(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000762 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
763 CapturedStmtInfo->lookup(OrigVD) != nullptr,
764 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
765 auto *OrigAddr = EmitLValue(&DRE).getAddress();
766 OMPPrivateScope VarScope(*this);
767 VarScope.addPrivate(OrigVD,
768 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
769 (void)VarScope.Privatize();
770 EmitIgnoredExpr(F);
771 }
772 ++IC;
773 }
774 emitLinearClauseFinal(*this, D);
775}
776
Alexander Musman515ad8c2014-05-22 08:54:05 +0000777void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000778 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000779 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000780 // for (IV in 0..LastIteration) BODY;
781 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000782 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000783 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000784
Alexey Bataev62dbb972015-04-22 11:59:37 +0000785 // Emit: if (PreCond) - begin.
786 // If the condition constant folds and can be elided, avoid emitting the
787 // whole loop.
788 bool CondConstant;
789 llvm::BasicBlock *ContBlock = nullptr;
790 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
791 if (!CondConstant)
792 return;
793 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000794 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
795 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000796 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
797 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000798 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000799 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000800 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000801
802 // Emit the loop iteration variable.
803 const Expr *IVExpr = S.getIterationVariable();
804 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
805 CGF.EmitVarDecl(*IVDecl);
806 CGF.EmitIgnoredExpr(S.getInit());
807
808 // Emit the iterations count variable.
809 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000810 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000811 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
812 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
813 // Emit calculation of the iterations count.
814 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000815 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000816
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000817 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000818
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000819 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000820 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000821 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000822 {
823 OMPPrivateScope LoopScope(CGF);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000824 emitPrivateLoopCounters(CGF, LoopScope, S.counters());
825 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000826 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000827 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000828 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000829 (void)LoopScope.Privatize();
830 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
Alexey Bataevae05c292015-06-16 11:59:36 +0000831 S.getCond(), S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000832 [&S](CodeGenFunction &CGF) {
833 CGF.EmitOMPLoopBody(S);
834 CGF.EmitStopPoint(&S);
835 },
836 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000837 // Emit final copy of the lastprivate variables at the end of loops.
838 if (HasLastprivateClause) {
839 CGF.EmitOMPLastprivateClauseFinal(S);
840 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000841 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000842 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000843 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000844 // Emit: if (PreCond) - end.
845 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000846 CGF.EmitBranch(ContBlock);
847 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000848 }
849 };
850 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000851}
852
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000853void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
854 const OMPLoopDirective &S,
855 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000856 bool Ordered, llvm::Value *LB,
857 llvm::Value *UB, llvm::Value *ST,
858 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000859 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000860
861 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000862 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000863
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000864 assert((Ordered ||
865 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000866 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000867
868 // Emit outer loop.
869 //
870 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000871 // When schedule(dynamic,chunk_size) is specified, the iterations are
872 // distributed to threads in the team in chunks as the threads request them.
873 // Each thread executes a chunk of iterations, then requests another chunk,
874 // until no chunks remain to be distributed. Each chunk contains chunk_size
875 // iterations, except for the last chunk to be distributed, which may have
876 // fewer iterations. When no chunk_size is specified, it defaults to 1.
877 //
878 // When schedule(guided,chunk_size) is specified, the iterations are assigned
879 // to threads in the team in chunks as the executing threads request them.
880 // Each thread executes a chunk of iterations, then requests another chunk,
881 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
882 // each chunk is proportional to the number of unassigned iterations divided
883 // by the number of threads in the team, decreasing to 1. For a chunk_size
884 // with value k (greater than 1), the size of each chunk is determined in the
885 // same way, with the restriction that the chunks do not contain fewer than k
886 // iterations (except for the last chunk to be assigned, which may have fewer
887 // than k iterations).
888 //
889 // When schedule(auto) is specified, the decision regarding scheduling is
890 // delegated to the compiler and/or runtime system. The programmer gives the
891 // implementation the freedom to choose any possible mapping of iterations to
892 // threads in the team.
893 //
894 // When schedule(runtime) is specified, the decision regarding scheduling is
895 // deferred until run time, and the schedule and chunk size are taken from the
896 // run-sched-var ICV. If the ICV is set to auto, the schedule is
897 // implementation defined
898 //
899 // while(__kmpc_dispatch_next(&LB, &UB)) {
900 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000901 // while (idx <= UB) { BODY; ++idx;
902 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
903 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000904 // }
905 //
906 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000907 // When schedule(static, chunk_size) is specified, iterations are divided into
908 // chunks of size chunk_size, and the chunks are assigned to the threads in
909 // the team in a round-robin fashion in the order of the thread number.
910 //
911 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
912 // while (idx <= UB) { BODY; ++idx; } // inner loop
913 // LB = LB + ST;
914 // UB = UB + ST;
915 // }
916 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000917
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000918 const Expr *IVExpr = S.getIterationVariable();
919 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
920 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
921
Alexander Musman92bdaab2015-03-12 13:37:50 +0000922 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000923 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
924 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
925 : UB),
926 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000927
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000928 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
929
930 // Start the loop with a block that tests the condition.
931 auto CondBlock = createBasicBlock("omp.dispatch.cond");
932 EmitBlock(CondBlock);
933 LoopStack.push(CondBlock);
934
935 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000936 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000937 // UB = min(UB, GlobalUB)
938 EmitIgnoredExpr(S.getEnsureUpperBound());
939 // IV = LB
940 EmitIgnoredExpr(S.getInit());
941 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +0000942 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +0000943 } else {
944 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
945 IL, LB, UB, ST);
946 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000947
948 // If there are any cleanups between here and the loop-exit scope,
949 // create a block to stage a loop exit along.
950 auto ExitBlock = LoopExit.getBlock();
951 if (LoopScope.requiresCleanups())
952 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
953
954 auto LoopBody = createBasicBlock("omp.dispatch.body");
955 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
956 if (ExitBlock != LoopExit.getBlock()) {
957 EmitBlock(ExitBlock);
958 EmitBranchThroughCleanup(LoopExit);
959 }
960 EmitBlock(LoopBody);
961
Alexander Musman92bdaab2015-03-12 13:37:50 +0000962 // Emit "IV = LB" (in case of static schedule, we have already calculated new
963 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000964 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000965 EmitIgnoredExpr(S.getInit());
966
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000967 // Create a block for the increment.
968 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
969 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
970
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000971 // Generate !llvm.loop.parallel metadata for loads and stores for loops
972 // with dynamic/guided scheduling and without ordered clause.
973 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
974 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
975 ScheduleKind == OMPC_SCHEDULE_guided) &&
976 !Ordered);
977 } else {
978 EmitOMPSimdInit(S);
979 }
980
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000981 SourceLocation Loc = S.getLocStart();
982 EmitOMPInnerLoop(
Alexey Bataevae05c292015-06-16 11:59:36 +0000983 S, LoopScope.requiresCleanups(), S.getCond(),
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000984 S.getInc(),
985 [&S](CodeGenFunction &CGF) {
986 CGF.EmitOMPLoopBody(S);
987 CGF.EmitStopPoint(&S);
988 },
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000989 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
990 if (Ordered) {
991 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000992 CGF, Loc, IVSize, IVSigned);
993 }
994 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000995
996 EmitBlock(Continue.getBlock());
997 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000998 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000999 // Emit "LB = LB + Stride", "UB = UB + Stride".
1000 EmitIgnoredExpr(S.getNextLowerBound());
1001 EmitIgnoredExpr(S.getNextUpperBound());
1002 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001003
1004 EmitBranch(CondBlock);
1005 LoopStack.pop();
1006 // Emit the fall-through block.
1007 EmitBlock(LoopExit.getBlock());
1008
1009 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001010 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001011 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001012}
1013
Alexander Musmanc6388682014-12-15 07:07:06 +00001014/// \brief Emit a helper variable and return corresponding lvalue.
1015static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1016 const DeclRefExpr *Helper) {
1017 auto VDecl = cast<VarDecl>(Helper->getDecl());
1018 CGF.EmitVarDecl(*VDecl);
1019 return CGF.EmitLValue(Helper);
1020}
1021
Alexey Bataev040d5402015-05-12 08:35:28 +00001022static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1023emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1024 bool OuterRegion) {
1025 // Detect the loop schedule kind and chunk.
1026 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1027 llvm::Value *Chunk = nullptr;
1028 if (auto *C =
1029 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
1030 ScheduleKind = C->getScheduleKind();
1031 if (const auto *Ch = C->getChunkSize()) {
1032 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1033 if (OuterRegion) {
1034 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1035 CGF.EmitVarDecl(*ImpVar);
1036 CGF.EmitStoreThroughLValue(
1037 CGF.EmitAnyExpr(Ch),
1038 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1039 ImpVar->getType()));
1040 } else {
1041 Ch = ImpRef;
1042 }
1043 }
1044 if (!C->getHelperChunkSize() || !OuterRegion) {
1045 Chunk = CGF.EmitScalarExpr(Ch);
1046 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
1047 S.getIterationVariable()->getType());
1048 }
1049 }
1050 }
1051 return std::make_pair(Chunk, ScheduleKind);
1052}
1053
Alexey Bataev38e89532015-04-16 04:54:05 +00001054bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001055 // Emit the loop iteration variable.
1056 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1057 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1058 EmitVarDecl(*IVDecl);
1059
1060 // Emit the iterations count variable.
1061 // If it is not a variable, Sema decided to calculate iterations count on each
1062 // iteration (e.g., it is foldable into a constant).
1063 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1064 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1065 // Emit calculation of the iterations count.
1066 EmitIgnoredExpr(S.getCalcLastIteration());
1067 }
1068
1069 auto &RT = CGM.getOpenMPRuntime();
1070
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001072 // Check pre-condition.
1073 {
1074 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001075 // If the condition constant folds and can be elided, avoid emitting the
1076 // whole loop.
1077 bool CondConstant;
1078 llvm::BasicBlock *ContBlock = nullptr;
1079 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1080 if (!CondConstant)
1081 return false;
1082 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001083 auto *ThenBlock = createBasicBlock("omp.precond.then");
1084 ContBlock = createBasicBlock("omp.precond.end");
1085 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001086 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001087 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001088 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001089 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001090
1091 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001092 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001093 // Emit 'then' code.
1094 {
1095 // Emit helper vars inits.
1096 LValue LB =
1097 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1098 LValue UB =
1099 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1100 LValue ST =
1101 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1102 LValue IL =
1103 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1104
1105 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001106 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1107 // Emit implicit barrier to synchronize threads and avoid data races on
1108 // initialization of firstprivate variables.
1109 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1110 OMPD_unknown);
1111 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001112 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001113 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001114 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001115 emitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001116 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001117 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001118
1119 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001120 llvm::Value *Chunk;
1121 OpenMPScheduleClauseKind ScheduleKind;
1122 auto ScheduleInfo =
1123 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1124 Chunk = ScheduleInfo.first;
1125 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001126 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1127 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001128 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001129 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001130 /* Chunked */ Chunk != nullptr) &&
1131 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001132 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1133 EmitOMPSimdInit(S);
1134 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001135 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1136 // When no chunk_size is specified, the iteration space is divided into
1137 // chunks that are approximately equal in size, and at most one chunk is
1138 // distributed to each thread. Note that the size of the chunks is
1139 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001140 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001141 Ordered, IL.getAddress(), LB.getAddress(),
1142 UB.getAddress(), ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001143 // UB = min(UB, GlobalUB);
1144 EmitIgnoredExpr(S.getEnsureUpperBound());
1145 // IV = LB;
1146 EmitIgnoredExpr(S.getInit());
1147 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001148 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1149 S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001150 [&S](CodeGenFunction &CGF) {
1151 CGF.EmitOMPLoopBody(S);
1152 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001153 },
1154 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001155 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001156 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001157 } else {
1158 // Emit the outer loop, which requests its work chunk [LB..UB] from
1159 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001160 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1161 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1162 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001163 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001164 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001165 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1166 if (HasLastprivateClause)
1167 EmitOMPLastprivateClauseFinal(
1168 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001169 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001170 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1171 EmitOMPSimdFinal(S);
1172 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001173 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001174 if (ContBlock) {
1175 EmitBranch(ContBlock);
1176 EmitBlock(ContBlock, true);
1177 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001178 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001179 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001180}
1181
1182void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001183 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001184 bool HasLastprivates = false;
1185 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1186 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1187 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001188 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001189
1190 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001191 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001192 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1193 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001194}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001195
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001196void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1197 LexicalScope Scope(*this, S.getSourceRange());
1198 bool HasLastprivates = false;
1199 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1200 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1201 };
1202 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
1203
1204 // Emit an implicit barrier at the end.
1205 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
1206 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1207 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001208}
1209
Alexey Bataev2df54a02015-03-12 08:53:29 +00001210static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1211 const Twine &Name,
1212 llvm::Value *Init = nullptr) {
1213 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1214 if (Init)
1215 CGF.EmitScalarInit(Init, LVal);
1216 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001217}
1218
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001219static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1220 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001221 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1222 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1223 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001224 bool HasLastprivates = false;
1225 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001226 auto &C = CGF.CGM.getContext();
1227 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1228 // Emit helper vars inits.
1229 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1230 CGF.Builder.getInt32(0));
1231 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1232 LValue UB =
1233 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1234 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1235 CGF.Builder.getInt32(1));
1236 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1237 CGF.Builder.getInt32(0));
1238 // Loop counter.
1239 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1240 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001241 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001242 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001243 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001244 // Generate condition for loop.
1245 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1246 OK_Ordinary, S.getLocStart(),
1247 /*fpContractable=*/false);
1248 // Increment for loop counter.
1249 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1250 OK_Ordinary, S.getLocStart());
1251 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1252 // Iterate through all sections and emit a switch construct:
1253 // switch (IV) {
1254 // case 0:
1255 // <SectionStmt[0]>;
1256 // break;
1257 // ...
1258 // case <NumSection> - 1:
1259 // <SectionStmt[<NumSection> - 1]>;
1260 // break;
1261 // }
1262 // .omp.sections.exit:
1263 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1264 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1265 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1266 CS->size());
1267 unsigned CaseNumber = 0;
1268 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1269 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1270 CGF.EmitBlock(CaseBB);
1271 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1272 CGF.EmitStmt(*C);
1273 CGF.EmitBranch(ExitBB);
1274 }
1275 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1276 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001277
1278 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1279 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1280 // Emit implicit barrier to synchronize threads and avoid data races on
1281 // initialization of firstprivate variables.
1282 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1283 OMPD_unknown);
1284 }
Alexey Bataev73870832015-04-27 04:12:12 +00001285 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001286 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001287 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001288 (void)LoopScope.Privatize();
1289
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001290 // Emit static non-chunked loop.
1291 CGF.CGM.getOpenMPRuntime().emitForInit(
1292 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001293 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1294 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001295 // UB = min(UB, GlobalUB);
1296 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1297 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1298 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1299 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1300 // IV = LB;
1301 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1302 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001303 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1304 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001305 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001306 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001307 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001308
1309 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1310 if (HasLastprivates)
1311 CGF.EmitOMPLastprivateClauseFinal(
1312 S, CGF.Builder.CreateIsNotNull(
1313 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001314 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001316 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001317 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1318 // clause. Otherwise the barrier will be generated by the codegen for the
1319 // directive.
1320 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1321 // Emit implicit barrier to synchronize threads and avoid data races on
1322 // initialization of firstprivate variables.
1323 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1324 OMPD_unknown);
1325 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001326 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001327 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001328 // If only one section is found - no need to generate loop, emit as a single
1329 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001330 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001331 // No need to generate reductions for sections with single section region, we
1332 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001333 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001334 // No need to generate lastprivates for sections with single section region,
1335 // we can use original shared variable for all calculations with barrier at
1336 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001337 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001338 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1339 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1340 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001341 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001342 (void)SingleScope.Privatize();
1343
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001344 CGF.EmitStmt(Stmt);
1345 CGF.EnsureInsertPoint();
1346 };
1347 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1348 llvm::None, llvm::None,
1349 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001350 // Emit barrier for firstprivates, lastprivates or reductions only if
1351 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1352 // generated by the codegen for the directive.
1353 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1354 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001355 // Emit implicit barrier to synchronize threads and avoid data races on
1356 // initialization of firstprivate variables.
1357 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1358 OMPD_unknown);
1359 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001360 return OMPD_single;
1361}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001362
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001363void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1364 LexicalScope Scope(*this, S.getSourceRange());
1365 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001366 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001367 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001368 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001369 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001370}
1371
1372void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001373 LexicalScope Scope(*this, S.getSourceRange());
1374 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1375 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1376 CGF.EnsureInsertPoint();
1377 };
1378 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001379}
1380
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001381void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001382 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001383 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001384 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001385 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001386 // Check if there are any 'copyprivate' clauses associated with this
1387 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001388 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001389 // Build a list of copyprivate variables along with helper expressions
1390 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001391 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001392 auto *C = cast<OMPCopyprivateClause>(*I);
1393 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001394 DestExprs.append(C->destination_exprs().begin(),
1395 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001396 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001397 AssignmentOps.append(C->assignment_ops().begin(),
1398 C->assignment_ops().end());
1399 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001400 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001401 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001402 bool HasFirstprivates;
1403 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1404 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1405 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001406 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001407 (void)SingleScope.Privatize();
1408
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001409 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1410 CGF.EnsureInsertPoint();
1411 };
1412 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001413 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001414 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001415 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1416 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1417 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1418 CopyprivateVars.empty()) {
1419 CGM.getOpenMPRuntime().emitBarrierCall(
1420 *this, S.getLocStart(),
1421 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001422 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001423}
1424
Alexey Bataev8d690652014-12-04 07:23:53 +00001425void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001426 LexicalScope Scope(*this, S.getSourceRange());
1427 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1428 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1429 CGF.EnsureInsertPoint();
1430 };
1431 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001432}
1433
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001434void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001435 LexicalScope Scope(*this, S.getSourceRange());
1436 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1437 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1438 CGF.EnsureInsertPoint();
1439 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001440 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001441 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001442}
1443
Alexey Bataev671605e2015-04-13 05:28:11 +00001444void CodeGenFunction::EmitOMPParallelForDirective(
1445 const OMPParallelForDirective &S) {
1446 // Emit directive as a combined directive that consists of two implicit
1447 // directives: 'parallel' with 'for' directive.
1448 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001449 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001450 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1451 CGF.EmitOMPWorksharingLoop(S);
1452 // Emit implicit barrier at the end of parallel region, but this barrier
1453 // is at the end of 'for' directive, so emit it as the implicit barrier for
1454 // this 'for' directive.
1455 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1456 OMPD_parallel);
1457 };
1458 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001459}
1460
Alexander Musmane4e893b2014-09-23 09:33:00 +00001461void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001462 const OMPParallelForSimdDirective &S) {
1463 // Emit directive as a combined directive that consists of two implicit
1464 // directives: 'parallel' with 'for' directive.
1465 LexicalScope Scope(*this, S.getSourceRange());
1466 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1467 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1468 CGF.EmitOMPWorksharingLoop(S);
1469 // Emit implicit barrier at the end of parallel region, but this barrier
1470 // is at the end of 'for' directive, so emit it as the implicit barrier for
1471 // this 'for' directive.
1472 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1473 OMPD_parallel);
1474 };
1475 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001476}
1477
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001478void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001479 const OMPParallelSectionsDirective &S) {
1480 // Emit directive as a combined directive that consists of two implicit
1481 // directives: 'parallel' with 'sections' directive.
1482 LexicalScope Scope(*this, S.getSourceRange());
1483 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1484 (void)emitSections(CGF, S);
1485 // Emit implicit barrier at the end of parallel region.
1486 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1487 OMPD_parallel);
1488 };
1489 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001490}
1491
Alexey Bataev62b63b12015-03-10 07:28:44 +00001492void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1493 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001494 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001495 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1496 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1497 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001498 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001499 // The first function argument for tasks is a thread id, the second one is a
1500 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001501 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1502 // Get list of private variables.
1503 llvm::SmallVector<const Expr *, 8> PrivateVars;
1504 llvm::SmallVector<const Expr *, 8> PrivateCopies;
1505 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1506 auto *C = cast<OMPPrivateClause>(*I);
1507 auto IRef = C->varlist_begin();
1508 for (auto *IInit : C->private_copies()) {
1509 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1510 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1511 PrivateVars.push_back(*IRef);
1512 PrivateCopies.push_back(IInit);
1513 }
1514 ++IRef;
1515 }
1516 }
1517 EmittedAsPrivate.clear();
1518 // Get list of firstprivate variables.
1519 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1520 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1521 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1522 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1523 auto *C = cast<OMPFirstprivateClause>(*I);
1524 auto IRef = C->varlist_begin();
1525 auto IElemInitRef = C->inits().begin();
1526 for (auto *IInit : C->private_copies()) {
1527 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1528 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1529 FirstprivateVars.push_back(*IRef);
1530 FirstprivateCopies.push_back(IInit);
1531 FirstprivateInits.push_back(*IElemInitRef);
1532 }
1533 ++IRef, ++IElemInitRef;
1534 }
1535 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001536 // Build list of dependences.
1537 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1538 Dependences;
1539 for (auto &&I = S.getClausesOfKind(OMPC_depend); I; ++I) {
1540 auto *C = cast<OMPDependClause>(*I);
1541 for (auto *IRef : C->varlists()) {
1542 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1543 }
1544 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001545 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1546 CodeGenFunction &CGF) {
1547 // Set proper addresses for generated private copies.
1548 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1549 OMPPrivateScope Scope(CGF);
1550 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
1551 auto *CopyFn = CGF.Builder.CreateAlignedLoad(
1552 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)),
1553 CGF.PointerAlignInBytes);
1554 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad(
1555 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)),
1556 CGF.PointerAlignInBytes);
1557 // Map privates.
1558 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16>
1559 PrivatePtrs;
1560 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1561 CallArgs.push_back(PrivatesPtr);
1562 for (auto *E : PrivateVars) {
1563 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1564 auto *PrivatePtr =
1565 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1566 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1567 CallArgs.push_back(PrivatePtr);
1568 }
1569 for (auto *E : FirstprivateVars) {
1570 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1571 auto *PrivatePtr =
1572 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1573 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1574 CallArgs.push_back(PrivatePtr);
1575 }
1576 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1577 for (auto &&Pair : PrivatePtrs) {
1578 auto *Replacement =
1579 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes);
1580 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1581 }
1582 }
1583 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001584 if (*PartId) {
1585 // TODO: emit code for untied tasks.
1586 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001587 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001588 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001589 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001590 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001591 // Check if we should emit tied or untied task.
1592 bool Tied = !S.getSingleClause(OMPC_untied);
1593 // Check if the task is final
1594 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1595 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1596 // If the condition constant folds and can be elided, try to avoid emitting
1597 // the condition and the dead arm of the if/else.
1598 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1599 bool CondConstant;
1600 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1601 Final.setInt(CondConstant);
1602 else
1603 Final.setPointer(EvaluateExprAsBool(Cond));
1604 } else {
1605 // By default the task is not final.
1606 Final.setInt(/*IntVal=*/false);
1607 }
1608 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001609 const Expr *IfCond = nullptr;
1610 if (auto C = S.getSingleClause(OMPC_if)) {
1611 IfCond = cast<OMPIfClause>(C)->getCondition();
1612 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001613 CGM.getOpenMPRuntime().emitTaskCall(
1614 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001615 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001616 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001617}
1618
Alexey Bataev9f797f32015-02-05 05:57:51 +00001619void CodeGenFunction::EmitOMPTaskyieldDirective(
1620 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001621 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001622}
1623
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001624void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001625 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001626}
1627
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001628void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1629 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001630}
1631
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001632void CodeGenFunction::EmitOMPTaskgroupDirective(
1633 const OMPTaskgroupDirective &S) {
1634 LexicalScope Scope(*this, S.getSourceRange());
1635 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1636 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1637 CGF.EnsureInsertPoint();
1638 };
1639 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1640}
1641
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001642void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001643 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1644 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1645 auto FlushClause = cast<OMPFlushClause>(C);
1646 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1647 FlushClause->varlist_end());
1648 }
1649 return llvm::None;
1650 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001651}
1652
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001653void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1654 LexicalScope Scope(*this, S.getSourceRange());
1655 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1656 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1657 CGF.EnsureInsertPoint();
1658 };
1659 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001660}
1661
Alexey Bataevb57056f2015-01-22 06:17:56 +00001662static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1663 QualType SrcType, QualType DestType) {
1664 assert(CGF.hasScalarEvaluationKind(DestType) &&
1665 "DestType must have scalar evaluation kind.");
1666 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1667 return Val.isScalar()
1668 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1669 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1670 DestType);
1671}
1672
1673static CodeGenFunction::ComplexPairTy
1674convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1675 QualType DestType) {
1676 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1677 "DestType must have complex evaluation kind.");
1678 CodeGenFunction::ComplexPairTy ComplexVal;
1679 if (Val.isScalar()) {
1680 // Convert the input element to the element type of the complex.
1681 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1682 auto ScalarVal =
1683 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1684 ComplexVal = CodeGenFunction::ComplexPairTy(
1685 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1686 } else {
1687 assert(Val.isComplex() && "Must be a scalar or complex.");
1688 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1689 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1690 ComplexVal.first = CGF.EmitScalarConversion(
1691 Val.getComplexVal().first, SrcElementType, DestElementType);
1692 ComplexVal.second = CGF.EmitScalarConversion(
1693 Val.getComplexVal().second, SrcElementType, DestElementType);
1694 }
1695 return ComplexVal;
1696}
1697
Alexey Bataev5e018f92015-04-23 06:35:10 +00001698static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1699 LValue LVal, RValue RVal) {
1700 if (LVal.isGlobalReg()) {
1701 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1702 } else {
1703 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1704 : llvm::Monotonic,
1705 LVal.isVolatile(), /*IsInit=*/false);
1706 }
1707}
1708
1709static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1710 QualType RValTy) {
1711 switch (CGF.getEvaluationKind(LVal.getType())) {
1712 case TEK_Scalar:
1713 CGF.EmitStoreThroughLValue(
1714 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1715 LVal);
1716 break;
1717 case TEK_Complex:
1718 CGF.EmitStoreOfComplex(
1719 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1720 /*isInit=*/false);
1721 break;
1722 case TEK_Aggregate:
1723 llvm_unreachable("Must be a scalar or complex.");
1724 }
1725}
1726
Alexey Bataevb57056f2015-01-22 06:17:56 +00001727static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1728 const Expr *X, const Expr *V,
1729 SourceLocation Loc) {
1730 // v = x;
1731 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1732 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1733 LValue XLValue = CGF.EmitLValue(X);
1734 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001735 RValue Res = XLValue.isGlobalReg()
1736 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1737 : CGF.EmitAtomicLoad(XLValue, Loc,
1738 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001739 : llvm::Monotonic,
1740 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001741 // OpenMP, 2.12.6, atomic Construct
1742 // Any atomic construct with a seq_cst clause forces the atomically
1743 // performed operation to include an implicit flush operation without a
1744 // list.
1745 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001746 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001747 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001748}
1749
Alexey Bataevb8329262015-02-27 06:33:30 +00001750static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1751 const Expr *X, const Expr *E,
1752 SourceLocation Loc) {
1753 // x = expr;
1754 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001755 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001756 // OpenMP, 2.12.6, atomic Construct
1757 // Any atomic construct with a seq_cst clause forces the atomically
1758 // performed operation to include an implicit flush operation without a
1759 // list.
1760 if (IsSeqCst)
1761 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1762}
1763
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001764static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1765 RValue Update,
1766 BinaryOperatorKind BO,
1767 llvm::AtomicOrdering AO,
1768 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001769 auto &Context = CGF.CGM.getContext();
1770 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001771 // expression is simple and atomic is allowed for the given type for the
1772 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001773 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001774 !Update.getScalarVal()->getType()->isIntegerTy() ||
1775 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1776 (Update.getScalarVal()->getType() !=
1777 X.getAddress()->getType()->getPointerElementType())) ||
1778 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001779 !Context.getTargetInfo().hasBuiltinAtomic(
1780 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001781 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001782
1783 llvm::AtomicRMWInst::BinOp RMWOp;
1784 switch (BO) {
1785 case BO_Add:
1786 RMWOp = llvm::AtomicRMWInst::Add;
1787 break;
1788 case BO_Sub:
1789 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001790 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001791 RMWOp = llvm::AtomicRMWInst::Sub;
1792 break;
1793 case BO_And:
1794 RMWOp = llvm::AtomicRMWInst::And;
1795 break;
1796 case BO_Or:
1797 RMWOp = llvm::AtomicRMWInst::Or;
1798 break;
1799 case BO_Xor:
1800 RMWOp = llvm::AtomicRMWInst::Xor;
1801 break;
1802 case BO_LT:
1803 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1804 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1805 : llvm::AtomicRMWInst::Max)
1806 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1807 : llvm::AtomicRMWInst::UMax);
1808 break;
1809 case BO_GT:
1810 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1811 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1812 : llvm::AtomicRMWInst::Min)
1813 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1814 : llvm::AtomicRMWInst::UMin);
1815 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001816 case BO_Assign:
1817 RMWOp = llvm::AtomicRMWInst::Xchg;
1818 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001819 case BO_Mul:
1820 case BO_Div:
1821 case BO_Rem:
1822 case BO_Shl:
1823 case BO_Shr:
1824 case BO_LAnd:
1825 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001826 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001827 case BO_PtrMemD:
1828 case BO_PtrMemI:
1829 case BO_LE:
1830 case BO_GE:
1831 case BO_EQ:
1832 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001833 case BO_AddAssign:
1834 case BO_SubAssign:
1835 case BO_AndAssign:
1836 case BO_OrAssign:
1837 case BO_XorAssign:
1838 case BO_MulAssign:
1839 case BO_DivAssign:
1840 case BO_RemAssign:
1841 case BO_ShlAssign:
1842 case BO_ShrAssign:
1843 case BO_Comma:
1844 llvm_unreachable("Unsupported atomic update operation");
1845 }
1846 auto *UpdateVal = Update.getScalarVal();
1847 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1848 UpdateVal = CGF.Builder.CreateIntCast(
1849 IC, X.getAddress()->getType()->getPointerElementType(),
1850 X.getType()->hasSignedIntegerRepresentation());
1851 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001852 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1853 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001854}
1855
Alexey Bataev5e018f92015-04-23 06:35:10 +00001856std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001857 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1858 llvm::AtomicOrdering AO, SourceLocation Loc,
1859 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1860 // Update expressions are allowed to have the following forms:
1861 // x binop= expr; -> xrval + expr;
1862 // x++, ++x -> xrval + 1;
1863 // x--, --x -> xrval - 1;
1864 // x = x binop expr; -> xrval binop expr
1865 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001866 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1867 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001868 if (X.isGlobalReg()) {
1869 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1870 // 'xrval'.
1871 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1872 } else {
1873 // Perform compare-and-swap procedure.
1874 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001875 }
1876 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001877 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001878}
1879
1880static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1881 const Expr *X, const Expr *E,
1882 const Expr *UE, bool IsXLHSInRHSPart,
1883 SourceLocation Loc) {
1884 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1885 "Update expr in 'atomic update' must be a binary operator.");
1886 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1887 // Update expressions are allowed to have the following forms:
1888 // x binop= expr; -> xrval + expr;
1889 // x++, ++x -> xrval + 1;
1890 // x--, --x -> xrval - 1;
1891 // x = x binop expr; -> xrval binop expr
1892 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001893 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001894 LValue XLValue = CGF.EmitLValue(X);
1895 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001896 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001897 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1898 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1899 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1900 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1901 auto Gen =
1902 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1903 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1904 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1905 return CGF.EmitAnyExpr(UE);
1906 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001907 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1908 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1909 // OpenMP, 2.12.6, atomic Construct
1910 // Any atomic construct with a seq_cst clause forces the atomically
1911 // performed operation to include an implicit flush operation without a
1912 // list.
1913 if (IsSeqCst)
1914 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1915}
1916
1917static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1918 QualType SourceType, QualType ResType) {
1919 switch (CGF.getEvaluationKind(ResType)) {
1920 case TEK_Scalar:
1921 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1922 case TEK_Complex: {
1923 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1924 return RValue::getComplex(Res.first, Res.second);
1925 }
1926 case TEK_Aggregate:
1927 break;
1928 }
1929 llvm_unreachable("Must be a scalar or complex.");
1930}
1931
1932static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1933 bool IsPostfixUpdate, const Expr *V,
1934 const Expr *X, const Expr *E,
1935 const Expr *UE, bool IsXLHSInRHSPart,
1936 SourceLocation Loc) {
1937 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1938 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1939 RValue NewVVal;
1940 LValue VLValue = CGF.EmitLValue(V);
1941 LValue XLValue = CGF.EmitLValue(X);
1942 RValue ExprRValue = CGF.EmitAnyExpr(E);
1943 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1944 QualType NewVValType;
1945 if (UE) {
1946 // 'x' is updated with some additional value.
1947 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1948 "Update expr in 'atomic capture' must be a binary operator.");
1949 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1950 // Update expressions are allowed to have the following forms:
1951 // x binop= expr; -> xrval + expr;
1952 // x++, ++x -> xrval + 1;
1953 // x--, --x -> xrval - 1;
1954 // x = x binop expr; -> xrval binop expr
1955 // x = expr Op x; - > expr binop xrval;
1956 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1957 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1958 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1959 NewVValType = XRValExpr->getType();
1960 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1961 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1962 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1963 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1964 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1965 RValue Res = CGF.EmitAnyExpr(UE);
1966 NewVVal = IsPostfixUpdate ? XRValue : Res;
1967 return Res;
1968 };
1969 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1970 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1971 if (Res.first) {
1972 // 'atomicrmw' instruction was generated.
1973 if (IsPostfixUpdate) {
1974 // Use old value from 'atomicrmw'.
1975 NewVVal = Res.second;
1976 } else {
1977 // 'atomicrmw' does not provide new value, so evaluate it using old
1978 // value of 'x'.
1979 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1980 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1981 NewVVal = CGF.EmitAnyExpr(UE);
1982 }
1983 }
1984 } else {
1985 // 'x' is simply rewritten with some 'expr'.
1986 NewVValType = X->getType().getNonReferenceType();
1987 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1988 X->getType().getNonReferenceType());
1989 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1990 NewVVal = XRValue;
1991 return ExprRValue;
1992 };
1993 // Try to perform atomicrmw xchg, otherwise simple exchange.
1994 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1995 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1996 Loc, Gen);
1997 if (Res.first) {
1998 // 'atomicrmw' instruction was generated.
1999 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2000 }
2001 }
2002 // Emit post-update store to 'v' of old/new 'x' value.
2003 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002004 // OpenMP, 2.12.6, atomic Construct
2005 // Any atomic construct with a seq_cst clause forces the atomically
2006 // performed operation to include an implicit flush operation without a
2007 // list.
2008 if (IsSeqCst)
2009 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2010}
2011
Alexey Bataevb57056f2015-01-22 06:17:56 +00002012static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002013 bool IsSeqCst, bool IsPostfixUpdate,
2014 const Expr *X, const Expr *V, const Expr *E,
2015 const Expr *UE, bool IsXLHSInRHSPart,
2016 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002017 switch (Kind) {
2018 case OMPC_read:
2019 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2020 break;
2021 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002022 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2023 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002024 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002025 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002026 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2027 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002028 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002029 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2030 IsXLHSInRHSPart, Loc);
2031 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002032 case OMPC_if:
2033 case OMPC_final:
2034 case OMPC_num_threads:
2035 case OMPC_private:
2036 case OMPC_firstprivate:
2037 case OMPC_lastprivate:
2038 case OMPC_reduction:
2039 case OMPC_safelen:
2040 case OMPC_collapse:
2041 case OMPC_default:
2042 case OMPC_seq_cst:
2043 case OMPC_shared:
2044 case OMPC_linear:
2045 case OMPC_aligned:
2046 case OMPC_copyin:
2047 case OMPC_copyprivate:
2048 case OMPC_flush:
2049 case OMPC_proc_bind:
2050 case OMPC_schedule:
2051 case OMPC_ordered:
2052 case OMPC_nowait:
2053 case OMPC_untied:
2054 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002055 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002056 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002057 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2058 }
2059}
2060
2061void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
2062 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
2063 OpenMPClauseKind Kind = OMPC_unknown;
2064 for (auto *C : S.clauses()) {
2065 // Find first clause (skip seq_cst clause, if it is first).
2066 if (C->getClauseKind() != OMPC_seq_cst) {
2067 Kind = C->getClauseKind();
2068 break;
2069 }
2070 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002071
2072 const auto *CS =
2073 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002074 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002075 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002076 }
2077 // Processing for statements under 'atomic capture'.
2078 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2079 for (const auto *C : Compound->body()) {
2080 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2081 enterFullExpression(EWC);
2082 }
2083 }
2084 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002085
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002086 LexicalScope Scope(*this, S.getSourceRange());
2087 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002088 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2089 S.getV(), S.getExpr(), S.getUpdateExpr(),
2090 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002091 };
2092 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002093}
2094
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002095void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2096 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2097}
2098
Alexey Bataev13314bf2014-10-09 04:18:56 +00002099void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2100 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2101}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002102
2103void CodeGenFunction::EmitOMPCancellationPointDirective(
2104 const OMPCancellationPointDirective &S) {
2105 llvm_unreachable(
2106 "CodeGen for 'omp cancellation point' is not supported yet.");
2107}
2108