blob: 45fa610b314c9e25da3a16d9e59b7855cc1d9952 [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
Alexey Bataev2377fe92015-09-10 08:12:02 +000023void CodeGenFunction::GenerateOpenMPCapturedVars(
24 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
25 const RecordDecl *RD = S.getCapturedRecordDecl();
26 auto CurField = RD->field_begin();
27 auto CurCap = S.captures().begin();
28 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
29 E = S.capture_init_end();
30 I != E; ++I, ++CurField, ++CurCap) {
31 if (CurField->hasCapturedVLAType()) {
32 auto VAT = CurField->getCapturedVLAType();
33 CapturedVars.push_back(VLASizeMap[VAT->getSizeExpr()]);
34 } else if (CurCap->capturesThis())
35 CapturedVars.push_back(CXXThisValue);
36 else
37 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
38 }
39}
40
41llvm::Function *
42CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
43 assert(
44 CapturedStmtInfo &&
45 "CapturedStmtInfo should be set when generating the captured function");
46 const CapturedDecl *CD = S.getCapturedDecl();
47 const RecordDecl *RD = S.getCapturedRecordDecl();
48 assert(CD->hasBody() && "missing CapturedDecl body");
49
50 // Build the argument list.
51 ASTContext &Ctx = CGM.getContext();
52 FunctionArgList Args;
53 Args.append(CD->param_begin(),
54 std::next(CD->param_begin(), CD->getContextParamPosition()));
55 auto I = S.captures().begin();
56 for (auto *FD : RD->fields()) {
57 QualType ArgType = FD->getType();
58 IdentifierInfo *II = nullptr;
59 VarDecl *CapVar = nullptr;
60 if (I->capturesVariable()) {
61 CapVar = I->getCapturedVar();
62 II = CapVar->getIdentifier();
63 } else if (I->capturesThis())
64 II = &getContext().Idents.get("this");
65 else {
66 assert(I->capturesVariableArrayType());
67 II = &getContext().Idents.get("vla");
68 }
69 if (ArgType->isVariablyModifiedType())
70 ArgType = getContext().getVariableArrayDecayedType(ArgType);
71 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
72 FD->getLocation(), II, ArgType));
73 ++I;
74 }
75 Args.append(
76 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
77 CD->param_end());
78
79 // Create the function declaration.
80 FunctionType::ExtInfo ExtInfo;
81 const CGFunctionInfo &FuncInfo =
82 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
83 /*IsVariadic=*/false);
84 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
85
86 llvm::Function *F = llvm::Function::Create(
87 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
88 CapturedStmtInfo->getHelperName(), &CGM.getModule());
89 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
90 if (CD->isNothrow())
91 F->addFnAttr(llvm::Attribute::NoUnwind);
92
93 // Generate the function.
94 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
95 CD->getBody()->getLocStart());
96 unsigned Cnt = CD->getContextParamPosition();
97 I = S.captures().begin();
98 for (auto *FD : RD->fields()) {
99 LValue ArgLVal =
100 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
101 AlignmentSource::Decl);
102 if (FD->hasCapturedVLAType()) {
103 auto *ExprArg =
104 EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
105 auto VAT = FD->getCapturedVLAType();
106 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
107 } else if (I->capturesVariable()) {
108 auto *Var = I->getCapturedVar();
109 QualType VarTy = Var->getType();
110 Address ArgAddr = ArgLVal.getAddress();
111 if (!VarTy->isReferenceType()) {
112 ArgAddr = EmitLoadOfReference(
113 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
114 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000115 setAddrOfLocalVar(
116 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000117 } else {
118 // If 'this' is captured, load it into CXXThisValue.
119 assert(I->capturesThis());
120 CXXThisValue =
121 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
122 }
123 ++Cnt, ++I;
124 }
125
126 PGO.assignRegionCounters(CD, F);
127 CapturedStmtInfo->EmitBody(*this, CD->getBody());
128 FinishFunction(CD->getBodyRBrace());
129
130 return F;
131}
132
Alexey Bataev9959db52014-05-06 10:08:46 +0000133//===----------------------------------------------------------------------===//
134// OpenMP Directive Emission
135//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000136void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000137 Address DestAddr, Address SrcAddr, QualType OriginalType,
138 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000139 // Perform element-by-element initialization.
140 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000141
142 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000143 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000144 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
145 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
146
147 auto SrcBegin = SrcAddr.getPointer();
148 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000149 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000150 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
151 // The basic structure here is a while-do loop.
152 auto BodyBB = createBasicBlock("omp.arraycpy.body");
153 auto DoneBB = createBasicBlock("omp.arraycpy.done");
154 auto IsEmpty =
155 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
156 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000157
Alexey Bataev420d45b2015-04-14 05:11:24 +0000158 // Enter the loop body, making that address the current address.
159 auto EntryBB = Builder.GetInsertBlock();
160 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000161
162 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
163
164 llvm::PHINode *SrcElementPHI =
165 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
166 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
167 Address SrcElementCurrent =
168 Address(SrcElementPHI,
169 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
170
171 llvm::PHINode *DestElementPHI =
172 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
173 DestElementPHI->addIncoming(DestBegin, EntryBB);
174 Address DestElementCurrent =
175 Address(DestElementPHI,
176 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000177
Alexey Bataev420d45b2015-04-14 05:11:24 +0000178 // Emit copy.
179 CopyGen(DestElementCurrent, SrcElementCurrent);
180
181 // Shift the address forward by one element.
182 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000183 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000184 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000185 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000186 // Check whether we've reached the end.
187 auto Done =
188 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
189 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000190 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
191 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000192
193 // Done.
194 EmitBlock(DoneBB, /*IsFinished=*/true);
195}
196
John McCall7f416cc2015-09-08 08:05:57 +0000197void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
198 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000199 const VarDecl *SrcVD, const Expr *Copy) {
200 if (OriginalType->isArrayType()) {
201 auto *BO = dyn_cast<BinaryOperator>(Copy);
202 if (BO && BO->getOpcode() == BO_Assign) {
203 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000204 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000205 } else {
206 // For arrays with complex element types perform element by element
207 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000208 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000209 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000210 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000211 // Working with the single array element, so have to remap
212 // destination and source variables to corresponding array
213 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000214 CodeGenFunction::OMPPrivateScope Remap(*this);
215 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000216 return DestElement;
217 });
218 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000219 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000220 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000221 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000222 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000223 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000224 } else {
225 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000226 CodeGenFunction::OMPPrivateScope Remap(*this);
227 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
228 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000229 (void)Remap.Privatize();
230 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000231 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000232 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000233}
234
Alexey Bataev69c62a92015-04-15 04:52:20 +0000235bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
236 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000237 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000238 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000239 auto IRef = C->varlist_begin();
240 auto InitsRef = C->inits().begin();
241 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000242 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000243 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
244 EmittedAsFirstprivate.insert(OrigVD);
245 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
246 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
247 bool IsRegistered;
248 DeclRefExpr DRE(
249 const_cast<VarDecl *>(OrigVD),
250 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
251 OrigVD) != nullptr,
252 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000253 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000254 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000255 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000256 // Emit VarDecl with copy init for arrays.
257 // Get the address of the original variable captured in current
258 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000259 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000260 auto Emission = EmitAutoVarAlloca(*VD);
261 auto *Init = VD->getInit();
262 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
263 // Perform simple memcpy.
264 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000265 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000266 } else {
267 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000268 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000269 [this, VDInit, Init](Address DestElement,
270 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000271 // Clean up any temporaries needed by the initialization.
272 RunCleanupsScope InitScope(*this);
273 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000274 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000275 EmitAnyExprToMem(Init, DestElement,
276 Init->getType().getQualifiers(),
277 /*IsInitializer*/ false);
278 LocalDeclMap.erase(VDInit);
279 });
280 }
281 EmitAutoVarCleanups(Emission);
282 return Emission.getAllocatedAddress();
283 });
284 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000285 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000286 // Emit private VarDecl with copy init.
287 // Remap temp VDInit variable to the address of the original
288 // variable
289 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000290 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000291 EmitDecl(*VD);
292 LocalDeclMap.erase(VDInit);
293 return GetAddrOfLocalVar(VD);
294 });
295 }
296 assert(IsRegistered &&
297 "firstprivate var already registered as private");
298 // Silence the warning about unused variable.
299 (void)IsRegistered;
300 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000301 ++IRef, ++InitsRef;
302 }
303 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000304 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000305}
306
Alexey Bataev03b340a2014-10-21 03:16:40 +0000307void CodeGenFunction::EmitOMPPrivateClause(
308 const OMPExecutableDirective &D,
309 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000310 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000311 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000312 auto IRef = C->varlist_begin();
313 for (auto IInit : C->private_copies()) {
314 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000315 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
316 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
317 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000318 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000319 // Emit private VarDecl with copy init.
320 EmitDecl(*VD);
321 return GetAddrOfLocalVar(VD);
322 });
323 assert(IsRegistered && "private var already registered as private");
324 // Silence the warning about unused variable.
325 (void)IsRegistered;
326 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000327 ++IRef;
328 }
329 }
330}
331
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000332bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
333 // threadprivate_var1 = master_threadprivate_var1;
334 // operator=(threadprivate_var2, master_threadprivate_var2);
335 // ...
336 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000337 llvm::DenseSet<const VarDecl *> CopiedVars;
338 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000339 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000340 auto IRef = C->varlist_begin();
341 auto ISrcRef = C->source_exprs().begin();
342 auto IDestRef = C->destination_exprs().begin();
343 for (auto *AssignOp : C->assignment_ops()) {
344 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000345 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000346 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000347
348 // Get the address of the master variable. If we are emitting code with
349 // TLS support, the address is passed from the master as field in the
350 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000351 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000352 if (getLangOpts().OpenMPUseTLS &&
353 getContext().getTargetInfo().isTLSSupported()) {
354 assert(CapturedStmtInfo->lookup(VD) &&
355 "Copyin threadprivates should have been captured!");
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
357 VK_LValue, (*IRef)->getExprLoc());
358 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000359 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000360 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000361 MasterAddr =
362 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
363 : CGM.GetAddrOfGlobal(VD),
364 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000365 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000366 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000367 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000368 if (CopiedVars.size() == 1) {
369 // At first check if current thread is a master thread. If it is, no
370 // need to copy data.
371 CopyBegin = createBasicBlock("copyin.not.master");
372 CopyEnd = createBasicBlock("copyin.not.master.end");
373 Builder.CreateCondBr(
374 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000375 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
376 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000377 CopyBegin, CopyEnd);
378 EmitBlock(CopyBegin);
379 }
380 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
381 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000382 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000383 }
384 ++IRef;
385 ++ISrcRef;
386 ++IDestRef;
387 }
388 }
389 if (CopyEnd) {
390 // Exit out of copying procedure for non-master thread.
391 EmitBlock(CopyEnd, /*IsFinished=*/true);
392 return true;
393 }
394 return false;
395}
396
Alexey Bataev38e89532015-04-16 04:54:05 +0000397bool CodeGenFunction::EmitOMPLastprivateClauseInit(
398 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000399 bool HasAtLeastOneLastprivate = false;
400 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000401 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000402 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000403 auto IRef = C->varlist_begin();
404 auto IDestRef = C->destination_exprs().begin();
405 for (auto *IInit : C->private_copies()) {
406 // Keep the address of the original variable for future update at the end
407 // of the loop.
408 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
409 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
410 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000411 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000412 DeclRefExpr DRE(
413 const_cast<VarDecl *>(OrigVD),
414 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
415 OrigVD) != nullptr,
416 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
417 return EmitLValue(&DRE).getAddress();
418 });
419 // Check if the variable is also a firstprivate: in this case IInit is
420 // not generated. Initialization of this variable will happen in codegen
421 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000422 if (IInit) {
423 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
424 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000425 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000426 // Emit private VarDecl with copy init.
427 EmitDecl(*VD);
428 return GetAddrOfLocalVar(VD);
429 });
430 assert(IsRegistered &&
431 "lastprivate var already registered as private");
432 (void)IsRegistered;
433 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000434 }
435 ++IRef, ++IDestRef;
436 }
437 }
438 return HasAtLeastOneLastprivate;
439}
440
441void CodeGenFunction::EmitOMPLastprivateClauseFinal(
442 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
443 // Emit following code:
444 // if (<IsLastIterCond>) {
445 // orig_var1 = private_orig_var1;
446 // ...
447 // orig_varn = private_orig_varn;
448 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000449 llvm::BasicBlock *ThenBB = nullptr;
450 llvm::BasicBlock *DoneBB = nullptr;
451 if (IsLastIterCond) {
452 ThenBB = createBasicBlock(".omp.lastprivate.then");
453 DoneBB = createBasicBlock(".omp.lastprivate.done");
454 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
455 EmitBlock(ThenBB);
456 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000457 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
458 const Expr *LastIterVal = nullptr;
459 const Expr *IVExpr = nullptr;
460 const Expr *IncExpr = nullptr;
461 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000462 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
463 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
464 LoopDirective->getUpperBoundVariable())
465 ->getDecl())
466 ->getAnyInitializer();
467 IVExpr = LoopDirective->getIterationVariable();
468 IncExpr = LoopDirective->getInc();
469 auto IUpdate = LoopDirective->updates().begin();
470 for (auto *E : LoopDirective->counters()) {
471 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
472 LoopCountersAndUpdates[D] = *IUpdate;
473 ++IUpdate;
474 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000475 }
476 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000477 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000478 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000479 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000480 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000481 auto IRef = C->varlist_begin();
482 auto ISrcRef = C->source_exprs().begin();
483 auto IDestRef = C->destination_exprs().begin();
484 for (auto *AssignOp : C->assignment_ops()) {
485 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000486 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000487 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
488 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
489 // If lastprivate variable is a loop control variable for loop-based
490 // directive, update its value before copyin back to original
491 // variable.
492 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000493 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000494 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
495 IVExpr->getType().getQualifiers(),
496 /*IsInitializer=*/false);
497 EmitIgnoredExpr(IncExpr);
498 FirstLCV = false;
499 }
500 EmitIgnoredExpr(UpExpr);
501 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000502 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
503 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
504 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000505 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000506 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000507 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
508 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000509 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000510 Address(Builder.CreateLoad(PrivateAddr),
511 getNaturalTypeAlignment(RefTy->getPointeeType()));
512 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000513 }
514 ++IRef;
515 ++ISrcRef;
516 ++IDestRef;
517 }
518 }
519 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000520 if (IsLastIterCond) {
521 EmitBlock(DoneBB, /*IsFinished=*/true);
522 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000523}
524
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000525void CodeGenFunction::EmitOMPReductionClauseInit(
526 const OMPExecutableDirective &D,
527 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000528 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000529 auto ILHS = C->lhs_exprs().begin();
530 auto IRHS = C->rhs_exprs().begin();
531 for (auto IRef : C->varlists()) {
532 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
533 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
534 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
535 // Store the address of the original variable associated with the LHS
536 // implicit variable.
John McCall7f416cc2015-09-08 08:05:57 +0000537 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000538 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
539 CapturedStmtInfo->lookup(OrigVD) != nullptr,
540 IRef->getType(), VK_LValue, IRef->getExprLoc());
541 return EmitLValue(&DRE).getAddress();
542 });
543 // Emit reduction copy.
544 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000545 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000546 // Emit private VarDecl with reduction init.
547 EmitDecl(*PrivateVD);
548 return GetAddrOfLocalVar(PrivateVD);
549 });
550 assert(IsRegistered && "private var already registered as private");
551 // Silence the warning about unused variable.
552 (void)IsRegistered;
553 ++ILHS, ++IRHS;
554 }
555 }
556}
557
558void CodeGenFunction::EmitOMPReductionClauseFinal(
559 const OMPExecutableDirective &D) {
560 llvm::SmallVector<const Expr *, 8> LHSExprs;
561 llvm::SmallVector<const Expr *, 8> RHSExprs;
562 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000563 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000564 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000565 HasAtLeastOneReduction = true;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000566 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
567 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
568 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
569 }
570 if (HasAtLeastOneReduction) {
571 // Emit nowait reduction if nowait clause is present or directive is a
572 // parallel directive (it always has implicit barrier).
573 CGM.getOpenMPRuntime().emitReduction(
574 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000575 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000576 isOpenMPParallelDirective(D.getDirectiveKind()) ||
577 D.getDirectiveKind() == OMPD_simd,
578 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000579 }
580}
581
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000582static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
583 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000584 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000585 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000586 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000587 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
588 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000589 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000590 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000591 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000592 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000593 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
594 /*IgnoreResultAssign*/ true);
595 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
596 CGF, NumThreads, NumThreadsClause->getLocStart());
597 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000598 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000599 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000600 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
601 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
602 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000603 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000604 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
605 if (C->getNameModifier() == OMPD_unknown ||
606 C->getNameModifier() == OMPD_parallel) {
607 IfCond = C->getCondition();
608 break;
609 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000610 }
611 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000612 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000613}
614
615void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
616 LexicalScope Scope(*this, S.getSourceRange());
617 // Emit parallel region as a standalone region.
618 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
619 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000620 bool Copyins = CGF.EmitOMPCopyinClause(S);
621 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
622 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000623 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000624 // initialization of firstprivate variables or propagation master's thread
625 // values of threadprivate variables to local instances of that variables
626 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000627 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
628 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
629 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000630 }
631 CGF.EmitOMPPrivateClause(S, PrivateScope);
632 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
633 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000634 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000635 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000636 // Emit implicit barrier at the end of the 'parallel' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000637 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
638 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
639 /*ForceSimpleCall=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000640 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000641 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000642}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000643
Alexey Bataev0f34da12015-07-02 04:17:07 +0000644void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
645 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000646 RunCleanupsScope BodyScope(*this);
647 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000648 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000649 EmitIgnoredExpr(I);
650 }
Alexander Musman3276a272015-03-21 10:12:56 +0000651 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000652 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000653 for (auto U : C->updates()) {
654 EmitIgnoredExpr(U);
655 }
656 }
657
Alexander Musmana5f070a2014-10-01 06:03:56 +0000658 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000659 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000660 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000661 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000662 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000663 // The end (updates/cleanups).
664 EmitBlock(Continue.getBlock());
665 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000666 // TODO: Update lastprivates if the SeparateIter flag is true.
667 // This will be implemented in a follow-up OMPLastprivateClause patch, but
668 // result should be still correct without it, as we do not make these
669 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000670}
671
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000672void CodeGenFunction::EmitOMPInnerLoop(
673 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
674 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000675 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
676 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000677 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000678
679 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000680 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000681 EmitBlock(CondBlock);
682 LoopStack.push(CondBlock);
683
684 // If there are any cleanups between here and the loop-exit scope,
685 // create a block to stage a loop exit along.
686 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000687 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000688 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000689
Alexander Musmand196ef22014-10-07 08:57:09 +0000690 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000691
Alexey Bataev2df54a02015-03-12 08:53:29 +0000692 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000693 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000694 if (ExitBlock != LoopExit.getBlock()) {
695 EmitBlock(ExitBlock);
696 EmitBranchThroughCleanup(LoopExit);
697 }
698
699 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000700 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000701
702 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000703 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000704 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
705
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000706 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000707
708 // Emit "IV = IV + 1" and a back-edge to the condition block.
709 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000710 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000711 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000712 BreakContinueStack.pop_back();
713 EmitBranch(CondBlock);
714 LoopStack.pop();
715 // Emit the fall-through block.
716 EmitBlock(LoopExit.getBlock());
717}
718
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000719void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000720 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000721 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000722 for (auto Init : C->inits()) {
723 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000724 auto *OrigVD = cast<VarDecl>(
725 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
726 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
727 CapturedStmtInfo->lookup(OrigVD) != nullptr,
728 VD->getInit()->getType(), VK_LValue,
729 VD->getInit()->getExprLoc());
730 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
731 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000732 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000733 /*capturedByInit=*/false);
734 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000735 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000736 // Emit the linear steps for the linear clauses.
737 // If a step is not constant, it is pre-calculated before the loop.
738 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
739 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000740 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000741 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000742 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000743 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000744 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000745}
746
747static void emitLinearClauseFinal(CodeGenFunction &CGF,
748 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000749 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000750 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000751 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000752 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000753 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
754 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000755 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000756 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000757 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000758 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000759 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000760 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +0000761 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000762 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000763 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000764 }
765 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000766}
767
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000768static void emitAlignedClause(CodeGenFunction &CGF,
769 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000770 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000771 unsigned ClauseAlignment = 0;
772 if (auto AlignmentExpr = Clause->getAlignment()) {
773 auto AlignmentCI =
774 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
775 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000776 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000777 for (auto E : Clause->varlists()) {
778 unsigned Alignment = ClauseAlignment;
779 if (Alignment == 0) {
780 // OpenMP [2.8.1, Description]
781 // If no optional parameter is specified, implementation-defined default
782 // alignments for SIMD instructions on the target platforms are assumed.
783 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000784 CGF.getContext()
785 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
786 E->getType()->getPointeeType()))
787 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000788 }
789 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
790 "alignment is not power of 2");
791 if (Alignment != 0) {
792 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
793 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
794 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000795 }
796 }
797}
798
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000799static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000800 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +0000801 ArrayRef<Expr *> Counters,
802 ArrayRef<Expr *> PrivateCounters) {
803 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000804 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +0000805 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
806 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000807 Address Addr = Address::invalid();
808 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000809 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +0000810 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000811 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +0000812 Addr = VarEmission.getAllocatedAddress();
813 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000814 });
John McCall7f416cc2015-09-08 08:05:57 +0000815 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +0000816 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000817 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000818}
819
Alexey Bataev62dbb972015-04-22 11:59:37 +0000820static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
821 const Expr *Cond, llvm::BasicBlock *TrueBlock,
822 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000823 {
824 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000825 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
826 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000827 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000828 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +0000829 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000830 CGF.EmitIgnoredExpr(I);
831 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000832 }
833 // Check that loop is executed at least one time.
834 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
835}
836
Alexander Musman3276a272015-03-21 10:12:56 +0000837static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000838emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000839 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000840 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000841 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +0000842 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000843 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
844 auto *PrivateVD =
845 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000846 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000847 // Emit private VarDecl with copy init.
848 CGF.EmitVarDecl(*PrivateVD);
849 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +0000850 });
851 assert(IsRegistered && "linear var already registered as private");
852 // Silence the warning about unused variable.
853 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000854 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +0000855 }
856 }
857}
858
Alexey Bataev45bfad52015-08-21 12:19:04 +0000859static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
860 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000861 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +0000862 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
863 /*ignoreResult=*/true);
864 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
865 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
866 // In presence of finite 'safelen', it may be unsafe to mark all
867 // the memory instructions parallel, because loop-carried
868 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000869 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
870 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000871 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
872 /*ignoreResult=*/true);
873 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000874 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000875 // In presence of finite 'safelen', it may be unsafe to mark all
876 // the memory instructions parallel, because loop-carried
877 // dependences of 'safelen' iterations are possible.
878 CGF.LoopStack.setParallel(false);
879 }
880}
881
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000882void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
883 // Walk clauses and process safelen/lastprivate.
884 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000885 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +0000886 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000887}
888
889void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
890 auto IC = D.counters().begin();
891 for (auto F : D.finals()) {
892 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000893 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000894 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
895 CapturedStmtInfo->lookup(OrigVD) != nullptr,
896 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000897 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000898 OMPPrivateScope VarScope(*this);
899 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000900 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000901 (void)VarScope.Privatize();
902 EmitIgnoredExpr(F);
903 }
904 ++IC;
905 }
906 emitLinearClauseFinal(*this, D);
907}
908
Alexander Musman515ad8c2014-05-22 08:54:05 +0000909void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000910 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000911 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000912 // for (IV in 0..LastIteration) BODY;
913 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000914 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000915 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000916
Alexey Bataev62dbb972015-04-22 11:59:37 +0000917 // Emit: if (PreCond) - begin.
918 // If the condition constant folds and can be elided, avoid emitting the
919 // whole loop.
920 bool CondConstant;
921 llvm::BasicBlock *ContBlock = nullptr;
922 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
923 if (!CondConstant)
924 return;
925 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000926 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
927 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000928 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
929 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000930 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000931 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000932 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000933
934 // Emit the loop iteration variable.
935 const Expr *IVExpr = S.getIterationVariable();
936 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
937 CGF.EmitVarDecl(*IVDecl);
938 CGF.EmitIgnoredExpr(S.getInit());
939
940 // Emit the iterations count variable.
941 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000942 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000943 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
944 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
945 // Emit calculation of the iterations count.
946 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000947 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000948
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000949 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000950
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000951 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000952 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000953 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000954 {
955 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000956 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
957 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000958 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000959 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000960 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000961 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000962 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +0000963 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
964 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000965 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +0000966 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +0000967 CGF.EmitStopPoint(&S);
968 },
969 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000970 // Emit final copy of the lastprivate variables at the end of loops.
971 if (HasLastprivateClause) {
972 CGF.EmitOMPLastprivateClauseFinal(S);
973 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000974 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000975 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000976 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000977 // Emit: if (PreCond) - end.
978 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979 CGF.EmitBranch(ContBlock);
980 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000981 }
982 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000983 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000984}
985
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000986void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
987 const OMPLoopDirective &S,
988 OMPPrivateScope &LoopScope,
John McCall7f416cc2015-09-08 08:05:57 +0000989 bool Ordered, Address LB,
990 Address UB, Address ST,
991 Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000992 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000993
994 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000995 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000996
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000997 assert((Ordered ||
998 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000999 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001000
1001 // Emit outer loop.
1002 //
1003 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001004 // When schedule(dynamic,chunk_size) is specified, the iterations are
1005 // distributed to threads in the team in chunks as the threads request them.
1006 // Each thread executes a chunk of iterations, then requests another chunk,
1007 // until no chunks remain to be distributed. Each chunk contains chunk_size
1008 // iterations, except for the last chunk to be distributed, which may have
1009 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1010 //
1011 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1012 // to threads in the team in chunks as the executing threads request them.
1013 // Each thread executes a chunk of iterations, then requests another chunk,
1014 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1015 // each chunk is proportional to the number of unassigned iterations divided
1016 // by the number of threads in the team, decreasing to 1. For a chunk_size
1017 // with value k (greater than 1), the size of each chunk is determined in the
1018 // same way, with the restriction that the chunks do not contain fewer than k
1019 // iterations (except for the last chunk to be assigned, which may have fewer
1020 // than k iterations).
1021 //
1022 // When schedule(auto) is specified, the decision regarding scheduling is
1023 // delegated to the compiler and/or runtime system. The programmer gives the
1024 // implementation the freedom to choose any possible mapping of iterations to
1025 // threads in the team.
1026 //
1027 // When schedule(runtime) is specified, the decision regarding scheduling is
1028 // deferred until run time, and the schedule and chunk size are taken from the
1029 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1030 // implementation defined
1031 //
1032 // while(__kmpc_dispatch_next(&LB, &UB)) {
1033 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001034 // while (idx <= UB) { BODY; ++idx;
1035 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1036 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001037 // }
1038 //
1039 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001040 // When schedule(static, chunk_size) is specified, iterations are divided into
1041 // chunks of size chunk_size, and the chunks are assigned to the threads in
1042 // the team in a round-robin fashion in the order of the thread number.
1043 //
1044 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1045 // while (idx <= UB) { BODY; ++idx; } // inner loop
1046 // LB = LB + ST;
1047 // UB = UB + ST;
1048 // }
1049 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001050
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001051 const Expr *IVExpr = S.getIterationVariable();
1052 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1053 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1054
John McCall7f416cc2015-09-08 08:05:57 +00001055 if (DynamicOrOrdered) {
1056 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1057 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1058 IVSize, IVSigned, Ordered, UBVal, Chunk);
1059 } else {
1060 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1061 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1062 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001063
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001064 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1065
1066 // Start the loop with a block that tests the condition.
1067 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1068 EmitBlock(CondBlock);
1069 LoopStack.push(CondBlock);
1070
1071 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001072 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001073 // UB = min(UB, GlobalUB)
1074 EmitIgnoredExpr(S.getEnsureUpperBound());
1075 // IV = LB
1076 EmitIgnoredExpr(S.getInit());
1077 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001078 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001079 } else {
1080 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1081 IL, LB, UB, ST);
1082 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001083
1084 // If there are any cleanups between here and the loop-exit scope,
1085 // create a block to stage a loop exit along.
1086 auto ExitBlock = LoopExit.getBlock();
1087 if (LoopScope.requiresCleanups())
1088 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1089
1090 auto LoopBody = createBasicBlock("omp.dispatch.body");
1091 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1092 if (ExitBlock != LoopExit.getBlock()) {
1093 EmitBlock(ExitBlock);
1094 EmitBranchThroughCleanup(LoopExit);
1095 }
1096 EmitBlock(LoopBody);
1097
Alexander Musman92bdaab2015-03-12 13:37:50 +00001098 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1099 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001100 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001101 EmitIgnoredExpr(S.getInit());
1102
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001103 // Create a block for the increment.
1104 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1105 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1106
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001107 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1108 // with dynamic/guided scheduling and without ordered clause.
1109 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
1110 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
1111 ScheduleKind == OMPC_SCHEDULE_guided) &&
1112 !Ordered);
1113 } else {
1114 EmitOMPSimdInit(S);
1115 }
1116
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001117 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001118 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1119 [&S, LoopExit](CodeGenFunction &CGF) {
1120 CGF.EmitOMPLoopBody(S, LoopExit);
1121 CGF.EmitStopPoint(&S);
1122 },
1123 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1124 if (Ordered) {
1125 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1126 CGF, Loc, IVSize, IVSigned);
1127 }
1128 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001129
1130 EmitBlock(Continue.getBlock());
1131 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001132 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001133 // Emit "LB = LB + Stride", "UB = UB + Stride".
1134 EmitIgnoredExpr(S.getNextLowerBound());
1135 EmitIgnoredExpr(S.getNextUpperBound());
1136 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001137
1138 EmitBranch(CondBlock);
1139 LoopStack.pop();
1140 // Emit the fall-through block.
1141 EmitBlock(LoopExit.getBlock());
1142
1143 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001144 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001145 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001146}
1147
Alexander Musmanc6388682014-12-15 07:07:06 +00001148/// \brief Emit a helper variable and return corresponding lvalue.
1149static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1150 const DeclRefExpr *Helper) {
1151 auto VDecl = cast<VarDecl>(Helper->getDecl());
1152 CGF.EmitVarDecl(*VDecl);
1153 return CGF.EmitLValue(Helper);
1154}
1155
Alexey Bataev040d5402015-05-12 08:35:28 +00001156static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1157emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1158 bool OuterRegion) {
1159 // Detect the loop schedule kind and chunk.
1160 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1161 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001162 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001163 ScheduleKind = C->getScheduleKind();
1164 if (const auto *Ch = C->getChunkSize()) {
1165 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1166 if (OuterRegion) {
1167 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1168 CGF.EmitVarDecl(*ImpVar);
1169 CGF.EmitStoreThroughLValue(
1170 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001171 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1172 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001173 } else {
1174 Ch = ImpRef;
1175 }
1176 }
1177 if (!C->getHelperChunkSize() || !OuterRegion) {
1178 Chunk = CGF.EmitScalarExpr(Ch);
1179 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001180 S.getIterationVariable()->getType(),
1181 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001182 }
1183 }
1184 }
1185 return std::make_pair(Chunk, ScheduleKind);
1186}
1187
Alexey Bataev38e89532015-04-16 04:54:05 +00001188bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001189 // Emit the loop iteration variable.
1190 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1191 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1192 EmitVarDecl(*IVDecl);
1193
1194 // Emit the iterations count variable.
1195 // If it is not a variable, Sema decided to calculate iterations count on each
1196 // iteration (e.g., it is foldable into a constant).
1197 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1198 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1199 // Emit calculation of the iterations count.
1200 EmitIgnoredExpr(S.getCalcLastIteration());
1201 }
1202
1203 auto &RT = CGM.getOpenMPRuntime();
1204
Alexey Bataev38e89532015-04-16 04:54:05 +00001205 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001206 // Check pre-condition.
1207 {
1208 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001209 // If the condition constant folds and can be elided, avoid emitting the
1210 // whole loop.
1211 bool CondConstant;
1212 llvm::BasicBlock *ContBlock = nullptr;
1213 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1214 if (!CondConstant)
1215 return false;
1216 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001217 auto *ThenBlock = createBasicBlock("omp.precond.then");
1218 ContBlock = createBasicBlock("omp.precond.end");
1219 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001220 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001221 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001222 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001223 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001224
1225 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001226 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001227 // Emit 'then' code.
1228 {
1229 // Emit helper vars inits.
1230 LValue LB =
1231 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1232 LValue UB =
1233 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1234 LValue ST =
1235 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1236 LValue IL =
1237 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1238
1239 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001240 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1241 // Emit implicit barrier to synchronize threads and avoid data races on
1242 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001243 CGM.getOpenMPRuntime().emitBarrierCall(
1244 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1245 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001246 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001247 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001248 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001249 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001250 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1251 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001252 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001253 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001254
1255 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001256 llvm::Value *Chunk;
1257 OpenMPScheduleClauseKind ScheduleKind;
1258 auto ScheduleInfo =
1259 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1260 Chunk = ScheduleInfo.first;
1261 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001262 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1263 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001264 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001265 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001266 /* Chunked */ Chunk != nullptr) &&
1267 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001268 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1269 EmitOMPSimdInit(S);
1270 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001271 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1272 // When no chunk_size is specified, the iteration space is divided into
1273 // chunks that are approximately equal in size, and at most one chunk is
1274 // distributed to each thread. Note that the size of the chunks is
1275 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001276 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1277 IVSize, IVSigned, Ordered,
1278 IL.getAddress(), LB.getAddress(),
1279 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001280 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001281 // UB = min(UB, GlobalUB);
1282 EmitIgnoredExpr(S.getEnsureUpperBound());
1283 // IV = LB;
1284 EmitIgnoredExpr(S.getInit());
1285 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001286 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1287 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001288 [&S, LoopExit](CodeGenFunction &CGF) {
1289 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001290 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001291 },
1292 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001293 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001294 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001295 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001296 } else {
1297 // Emit the outer loop, which requests its work chunk [LB..UB] from
1298 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001299 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1300 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1301 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001302 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001303 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001304 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1305 if (HasLastprivateClause)
1306 EmitOMPLastprivateClauseFinal(
1307 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001308 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1310 EmitOMPSimdFinal(S);
1311 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001312 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001313 if (ContBlock) {
1314 EmitBranch(ContBlock);
1315 EmitBlock(ContBlock, true);
1316 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001317 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001318 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001319}
1320
1321void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001322 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001323 bool HasLastprivates = false;
1324 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1325 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1326 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001327 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1328 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001329
1330 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001331 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001332 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1333 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001334}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001335
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001336void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1337 LexicalScope Scope(*this, S.getSourceRange());
1338 bool HasLastprivates = false;
1339 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1340 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1341 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001342 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001343
1344 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001345 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001346 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1347 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001348}
1349
Alexey Bataev2df54a02015-03-12 08:53:29 +00001350static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1351 const Twine &Name,
1352 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001353 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001354 if (Init)
1355 CGF.EmitScalarInit(Init, LVal);
1356 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001357}
1358
Alexey Bataev0f34da12015-07-02 04:17:07 +00001359OpenMPDirectiveKind
1360CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001361 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1362 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1363 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001364 bool HasLastprivates = false;
1365 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001366 auto &C = CGF.CGM.getContext();
1367 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1368 // Emit helper vars inits.
1369 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1370 CGF.Builder.getInt32(0));
1371 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1372 LValue UB =
1373 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1374 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1375 CGF.Builder.getInt32(1));
1376 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1377 CGF.Builder.getInt32(0));
1378 // Loop counter.
1379 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1380 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001381 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001382 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001383 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001384 // Generate condition for loop.
1385 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1386 OK_Ordinary, S.getLocStart(),
1387 /*fpContractable=*/false);
1388 // Increment for loop counter.
1389 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1390 OK_Ordinary, S.getLocStart());
1391 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1392 // Iterate through all sections and emit a switch construct:
1393 // switch (IV) {
1394 // case 0:
1395 // <SectionStmt[0]>;
1396 // break;
1397 // ...
1398 // case <NumSection> - 1:
1399 // <SectionStmt[<NumSection> - 1]>;
1400 // break;
1401 // }
1402 // .omp.sections.exit:
1403 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1404 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1405 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1406 CS->size());
1407 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001408 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001409 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1410 CGF.EmitBlock(CaseBB);
1411 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001412 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001413 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001414 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001415 }
1416 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1417 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001418
1419 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1420 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1421 // Emit implicit barrier to synchronize threads and avoid data races on
1422 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001423 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1424 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1425 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001426 }
Alexey Bataev73870832015-04-27 04:12:12 +00001427 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001428 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001429 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001430 (void)LoopScope.Privatize();
1431
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001432 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001433 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001434 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001435 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1436 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001437 // UB = min(UB, GlobalUB);
1438 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1439 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1440 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1441 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1442 // IV = LB;
1443 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1444 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001445 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1446 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001447 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001448 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001449 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001450
1451 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1452 if (HasLastprivates)
1453 CGF.EmitOMPLastprivateClauseFinal(
1454 S, CGF.Builder.CreateIsNotNull(
1455 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001456 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001457
Alexey Bataev25e5b442015-09-15 12:52:43 +00001458 bool HasCancel = false;
1459 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1460 HasCancel = OSD->hasCancel();
1461 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1462 HasCancel = OPSD->hasCancel();
1463 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1464 HasCancel);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001465 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1466 // clause. Otherwise the barrier will be generated by the codegen for the
1467 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001468 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001469 // Emit implicit barrier to synchronize threads and avoid data races on
1470 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001471 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1472 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001473 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001474 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001475 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001476 // If only one section is found - no need to generate loop, emit as a single
1477 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001478 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001479 // No need to generate reductions for sections with single section region, we
1480 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001481 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001482 // No need to generate lastprivates for sections with single section region,
1483 // we can use original shared variable for all calculations with barrier at
1484 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001485 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001486 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1487 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1488 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001489 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001490 (void)SingleScope.Privatize();
1491
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001492 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001493 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001494 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1495 llvm::None, llvm::None, llvm::None,
1496 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001497 // Emit barrier for firstprivates, lastprivates or reductions only if
1498 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1499 // generated by the codegen for the directive.
1500 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001501 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001502 // Emit implicit barrier to synchronize threads and avoid data races on
1503 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001504 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown,
1505 /*EmitChecks=*/false,
1506 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001507 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001508 return OMPD_single;
1509}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001510
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001511void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1512 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001513 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001514 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001515 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001516 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001517 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001518}
1519
1520void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001521 LexicalScope Scope(*this, S.getSourceRange());
1522 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1523 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1524 CGF.EnsureInsertPoint();
1525 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001526 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1527 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001528}
1529
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001530void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001531 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001532 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001533 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001534 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001535 // Check if there are any 'copyprivate' clauses associated with this
1536 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001537 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001538 // Build a list of copyprivate variables along with helper expressions
1539 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001540 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001541 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001542 DestExprs.append(C->destination_exprs().begin(),
1543 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001544 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001545 AssignmentOps.append(C->assignment_ops().begin(),
1546 C->assignment_ops().end());
1547 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001548 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001549 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001550 bool HasFirstprivates;
1551 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1552 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1553 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001554 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001555 (void)SingleScope.Privatize();
1556
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001557 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1558 CGF.EnsureInsertPoint();
1559 };
1560 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001561 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001562 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001563 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1564 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001565 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001566 CopyprivateVars.empty()) {
1567 CGM.getOpenMPRuntime().emitBarrierCall(
1568 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001569 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001570 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001571}
1572
Alexey Bataev8d690652014-12-04 07:23:53 +00001573void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001574 LexicalScope Scope(*this, S.getSourceRange());
1575 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1576 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1577 CGF.EnsureInsertPoint();
1578 };
1579 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001580}
1581
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001582void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001583 LexicalScope Scope(*this, S.getSourceRange());
1584 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1585 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1586 CGF.EnsureInsertPoint();
1587 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001588 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001589 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001590}
1591
Alexey Bataev671605e2015-04-13 05:28:11 +00001592void CodeGenFunction::EmitOMPParallelForDirective(
1593 const OMPParallelForDirective &S) {
1594 // Emit directive as a combined directive that consists of two implicit
1595 // directives: 'parallel' with 'for' directive.
1596 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001597 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001598 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1599 CGF.EmitOMPWorksharingLoop(S);
1600 // Emit implicit barrier at the end of parallel region, but this barrier
1601 // is at the end of 'for' directive, so emit it as the implicit barrier for
1602 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001603 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1604 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1605 /*ForceSimpleCall=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001606 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001607 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001608}
1609
Alexander Musmane4e893b2014-09-23 09:33:00 +00001610void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001611 const OMPParallelForSimdDirective &S) {
1612 // Emit directive as a combined directive that consists of two implicit
1613 // directives: 'parallel' with 'for' directive.
1614 LexicalScope Scope(*this, S.getSourceRange());
1615 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1616 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1617 CGF.EmitOMPWorksharingLoop(S);
1618 // Emit implicit barrier at the end of parallel region, but this barrier
1619 // is at the end of 'for' directive, so emit it as the implicit barrier for
1620 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001621 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1622 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1623 /*ForceSimpleCall=*/true);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001624 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001625 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001626}
1627
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001628void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001629 const OMPParallelSectionsDirective &S) {
1630 // Emit directive as a combined directive that consists of two implicit
1631 // directives: 'parallel' with 'sections' directive.
1632 LexicalScope Scope(*this, S.getSourceRange());
1633 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001634 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001635 // Emit implicit barrier at the end of parallel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001636 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1637 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1638 /*ForceSimpleCall=*/true);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001639 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001640 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001641}
1642
Alexey Bataev62b63b12015-03-10 07:28:44 +00001643void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1644 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001645 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001646 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1647 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1648 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001649 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001650 // The first function argument for tasks is a thread id, the second one is a
1651 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001652 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1653 // Get list of private variables.
1654 llvm::SmallVector<const Expr *, 8> PrivateVars;
1655 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001656 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001657 auto IRef = C->varlist_begin();
1658 for (auto *IInit : C->private_copies()) {
1659 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1660 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1661 PrivateVars.push_back(*IRef);
1662 PrivateCopies.push_back(IInit);
1663 }
1664 ++IRef;
1665 }
1666 }
1667 EmittedAsPrivate.clear();
1668 // Get list of firstprivate variables.
1669 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1670 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1671 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001672 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001673 auto IRef = C->varlist_begin();
1674 auto IElemInitRef = C->inits().begin();
1675 for (auto *IInit : C->private_copies()) {
1676 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1677 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1678 FirstprivateVars.push_back(*IRef);
1679 FirstprivateCopies.push_back(IInit);
1680 FirstprivateInits.push_back(*IElemInitRef);
1681 }
1682 ++IRef, ++IElemInitRef;
1683 }
1684 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001685 // Build list of dependences.
1686 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1687 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001688 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001689 for (auto *IRef : C->varlists()) {
1690 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1691 }
1692 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001693 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1694 CodeGenFunction &CGF) {
1695 // Set proper addresses for generated private copies.
1696 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1697 OMPPrivateScope Scope(CGF);
1698 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001699 auto *CopyFn = CGF.Builder.CreateLoad(
1700 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1701 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1702 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001703 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001704 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001705 PrivatePtrs;
1706 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1707 CallArgs.push_back(PrivatesPtr);
1708 for (auto *E : PrivateVars) {
1709 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001710 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001711 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1712 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001713 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001714 }
1715 for (auto *E : FirstprivateVars) {
1716 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001717 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001718 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1719 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001720 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001721 }
1722 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1723 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00001724 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
1725 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001726 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1727 }
1728 }
1729 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001730 if (*PartId) {
1731 // TODO: emit code for untied tasks.
1732 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001733 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001734 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001735 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1736 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001737 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001738 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001739 // Check if the task is final
1740 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001741 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001742 // If the condition constant folds and can be elided, try to avoid emitting
1743 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001744 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001745 bool CondConstant;
1746 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1747 Final.setInt(CondConstant);
1748 else
1749 Final.setPointer(EvaluateExprAsBool(Cond));
1750 } else {
1751 // By default the task is not final.
1752 Final.setInt(/*IntVal=*/false);
1753 }
1754 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001755 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001756 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1757 if (C->getNameModifier() == OMPD_unknown ||
1758 C->getNameModifier() == OMPD_task) {
1759 IfCond = C->getCondition();
1760 break;
1761 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001762 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001763 CGM.getOpenMPRuntime().emitTaskCall(
1764 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001765 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001766 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001767}
1768
Alexey Bataev9f797f32015-02-05 05:57:51 +00001769void CodeGenFunction::EmitOMPTaskyieldDirective(
1770 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001771 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001772}
1773
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001774void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001775 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001776}
1777
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001778void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1779 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001780}
1781
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001782void CodeGenFunction::EmitOMPTaskgroupDirective(
1783 const OMPTaskgroupDirective &S) {
1784 LexicalScope Scope(*this, S.getSourceRange());
1785 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1786 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1787 CGF.EnsureInsertPoint();
1788 };
1789 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1790}
1791
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001792void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001793 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001794 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001795 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1796 FlushClause->varlist_end());
1797 }
1798 return llvm::None;
1799 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001800}
1801
Alexey Bataev5f600d62015-09-29 03:48:57 +00001802static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
1803 const CapturedStmt *S) {
1804 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1805 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
1806 CGF.CapturedStmtInfo = &CapStmtInfo;
1807 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
1808 Fn->addFnAttr(llvm::Attribute::NoInline);
1809 return Fn;
1810}
1811
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001812void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1813 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00001814 auto *C = S.getSingleClause<OMPSIMDClause>();
1815 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
1816 if (C) {
1817 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1818 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1819 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1820 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
1821 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
1822 } else {
1823 CGF.EmitStmt(
1824 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1825 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001826 CGF.EnsureInsertPoint();
1827 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00001828 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001829}
1830
Alexey Bataevb57056f2015-01-22 06:17:56 +00001831static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001832 QualType SrcType, QualType DestType,
1833 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001834 assert(CGF.hasScalarEvaluationKind(DestType) &&
1835 "DestType must have scalar evaluation kind.");
1836 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1837 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001838 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
1839 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00001840 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001841 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001842}
1843
1844static CodeGenFunction::ComplexPairTy
1845convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001846 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001847 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1848 "DestType must have complex evaluation kind.");
1849 CodeGenFunction::ComplexPairTy ComplexVal;
1850 if (Val.isScalar()) {
1851 // Convert the input element to the element type of the complex.
1852 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001853 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
1854 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001855 ComplexVal = CodeGenFunction::ComplexPairTy(
1856 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1857 } else {
1858 assert(Val.isComplex() && "Must be a scalar or complex.");
1859 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1860 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1861 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001862 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001863 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001864 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001865 }
1866 return ComplexVal;
1867}
1868
Alexey Bataev5e018f92015-04-23 06:35:10 +00001869static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1870 LValue LVal, RValue RVal) {
1871 if (LVal.isGlobalReg()) {
1872 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1873 } else {
1874 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1875 : llvm::Monotonic,
1876 LVal.isVolatile(), /*IsInit=*/false);
1877 }
1878}
1879
1880static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001881 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001882 switch (CGF.getEvaluationKind(LVal.getType())) {
1883 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001884 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
1885 CGF, RVal, RValTy, LVal.getType(), Loc)),
1886 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001887 break;
1888 case TEK_Complex:
1889 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001890 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001891 /*isInit=*/false);
1892 break;
1893 case TEK_Aggregate:
1894 llvm_unreachable("Must be a scalar or complex.");
1895 }
1896}
1897
Alexey Bataevb57056f2015-01-22 06:17:56 +00001898static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1899 const Expr *X, const Expr *V,
1900 SourceLocation Loc) {
1901 // v = x;
1902 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1903 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1904 LValue XLValue = CGF.EmitLValue(X);
1905 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001906 RValue Res = XLValue.isGlobalReg()
1907 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1908 : CGF.EmitAtomicLoad(XLValue, Loc,
1909 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001910 : llvm::Monotonic,
1911 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001912 // OpenMP, 2.12.6, atomic Construct
1913 // Any atomic construct with a seq_cst clause forces the atomically
1914 // performed operation to include an implicit flush operation without a
1915 // list.
1916 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001917 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001918 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001919}
1920
Alexey Bataevb8329262015-02-27 06:33:30 +00001921static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1922 const Expr *X, const Expr *E,
1923 SourceLocation Loc) {
1924 // x = expr;
1925 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001926 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001927 // OpenMP, 2.12.6, atomic Construct
1928 // Any atomic construct with a seq_cst clause forces the atomically
1929 // performed operation to include an implicit flush operation without a
1930 // list.
1931 if (IsSeqCst)
1932 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1933}
1934
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001935static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1936 RValue Update,
1937 BinaryOperatorKind BO,
1938 llvm::AtomicOrdering AO,
1939 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001940 auto &Context = CGF.CGM.getContext();
1941 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001942 // expression is simple and atomic is allowed for the given type for the
1943 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001944 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001945 !Update.getScalarVal()->getType()->isIntegerTy() ||
1946 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1947 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00001948 X.getAddress().getElementType())) ||
1949 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001950 !Context.getTargetInfo().hasBuiltinAtomic(
1951 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001952 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001953
1954 llvm::AtomicRMWInst::BinOp RMWOp;
1955 switch (BO) {
1956 case BO_Add:
1957 RMWOp = llvm::AtomicRMWInst::Add;
1958 break;
1959 case BO_Sub:
1960 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001961 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001962 RMWOp = llvm::AtomicRMWInst::Sub;
1963 break;
1964 case BO_And:
1965 RMWOp = llvm::AtomicRMWInst::And;
1966 break;
1967 case BO_Or:
1968 RMWOp = llvm::AtomicRMWInst::Or;
1969 break;
1970 case BO_Xor:
1971 RMWOp = llvm::AtomicRMWInst::Xor;
1972 break;
1973 case BO_LT:
1974 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1975 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1976 : llvm::AtomicRMWInst::Max)
1977 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1978 : llvm::AtomicRMWInst::UMax);
1979 break;
1980 case BO_GT:
1981 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1982 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1983 : llvm::AtomicRMWInst::Min)
1984 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1985 : llvm::AtomicRMWInst::UMin);
1986 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001987 case BO_Assign:
1988 RMWOp = llvm::AtomicRMWInst::Xchg;
1989 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001990 case BO_Mul:
1991 case BO_Div:
1992 case BO_Rem:
1993 case BO_Shl:
1994 case BO_Shr:
1995 case BO_LAnd:
1996 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001997 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001998 case BO_PtrMemD:
1999 case BO_PtrMemI:
2000 case BO_LE:
2001 case BO_GE:
2002 case BO_EQ:
2003 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002004 case BO_AddAssign:
2005 case BO_SubAssign:
2006 case BO_AndAssign:
2007 case BO_OrAssign:
2008 case BO_XorAssign:
2009 case BO_MulAssign:
2010 case BO_DivAssign:
2011 case BO_RemAssign:
2012 case BO_ShlAssign:
2013 case BO_ShrAssign:
2014 case BO_Comma:
2015 llvm_unreachable("Unsupported atomic update operation");
2016 }
2017 auto *UpdateVal = Update.getScalarVal();
2018 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2019 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002020 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002021 X.getType()->hasSignedIntegerRepresentation());
2022 }
John McCall7f416cc2015-09-08 08:05:57 +00002023 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002024 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002025}
2026
Alexey Bataev5e018f92015-04-23 06:35:10 +00002027std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002028 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2029 llvm::AtomicOrdering AO, SourceLocation Loc,
2030 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2031 // Update expressions are allowed to have the following forms:
2032 // x binop= expr; -> xrval + expr;
2033 // x++, ++x -> xrval + 1;
2034 // x--, --x -> xrval - 1;
2035 // x = x binop expr; -> xrval binop expr
2036 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002037 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2038 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002039 if (X.isGlobalReg()) {
2040 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2041 // 'xrval'.
2042 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2043 } else {
2044 // Perform compare-and-swap procedure.
2045 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002046 }
2047 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002048 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002049}
2050
2051static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2052 const Expr *X, const Expr *E,
2053 const Expr *UE, bool IsXLHSInRHSPart,
2054 SourceLocation Loc) {
2055 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2056 "Update expr in 'atomic update' must be a binary operator.");
2057 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2058 // Update expressions are allowed to have the following forms:
2059 // x binop= expr; -> xrval + expr;
2060 // x++, ++x -> xrval + 1;
2061 // x--, --x -> xrval - 1;
2062 // x = x binop expr; -> xrval binop expr
2063 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002064 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002065 LValue XLValue = CGF.EmitLValue(X);
2066 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002067 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002068 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2069 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2070 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2071 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2072 auto Gen =
2073 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2074 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2075 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2076 return CGF.EmitAnyExpr(UE);
2077 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002078 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2079 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2080 // OpenMP, 2.12.6, atomic Construct
2081 // Any atomic construct with a seq_cst clause forces the atomically
2082 // performed operation to include an implicit flush operation without a
2083 // list.
2084 if (IsSeqCst)
2085 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2086}
2087
2088static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002089 QualType SourceType, QualType ResType,
2090 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002091 switch (CGF.getEvaluationKind(ResType)) {
2092 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002093 return RValue::get(
2094 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002095 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002096 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002097 return RValue::getComplex(Res.first, Res.second);
2098 }
2099 case TEK_Aggregate:
2100 break;
2101 }
2102 llvm_unreachable("Must be a scalar or complex.");
2103}
2104
2105static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2106 bool IsPostfixUpdate, const Expr *V,
2107 const Expr *X, const Expr *E,
2108 const Expr *UE, bool IsXLHSInRHSPart,
2109 SourceLocation Loc) {
2110 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2111 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2112 RValue NewVVal;
2113 LValue VLValue = CGF.EmitLValue(V);
2114 LValue XLValue = CGF.EmitLValue(X);
2115 RValue ExprRValue = CGF.EmitAnyExpr(E);
2116 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2117 QualType NewVValType;
2118 if (UE) {
2119 // 'x' is updated with some additional value.
2120 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2121 "Update expr in 'atomic capture' must be a binary operator.");
2122 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2123 // Update expressions are allowed to have the following forms:
2124 // x binop= expr; -> xrval + expr;
2125 // x++, ++x -> xrval + 1;
2126 // x--, --x -> xrval - 1;
2127 // x = x binop expr; -> xrval binop expr
2128 // x = expr Op x; - > expr binop xrval;
2129 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2130 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2131 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2132 NewVValType = XRValExpr->getType();
2133 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2134 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2135 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2136 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2137 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2138 RValue Res = CGF.EmitAnyExpr(UE);
2139 NewVVal = IsPostfixUpdate ? XRValue : Res;
2140 return Res;
2141 };
2142 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2143 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2144 if (Res.first) {
2145 // 'atomicrmw' instruction was generated.
2146 if (IsPostfixUpdate) {
2147 // Use old value from 'atomicrmw'.
2148 NewVVal = Res.second;
2149 } else {
2150 // 'atomicrmw' does not provide new value, so evaluate it using old
2151 // value of 'x'.
2152 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2153 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2154 NewVVal = CGF.EmitAnyExpr(UE);
2155 }
2156 }
2157 } else {
2158 // 'x' is simply rewritten with some 'expr'.
2159 NewVValType = X->getType().getNonReferenceType();
2160 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002161 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002162 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2163 NewVVal = XRValue;
2164 return ExprRValue;
2165 };
2166 // Try to perform atomicrmw xchg, otherwise simple exchange.
2167 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2168 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2169 Loc, Gen);
2170 if (Res.first) {
2171 // 'atomicrmw' instruction was generated.
2172 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2173 }
2174 }
2175 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002176 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002177 // OpenMP, 2.12.6, atomic Construct
2178 // Any atomic construct with a seq_cst clause forces the atomically
2179 // performed operation to include an implicit flush operation without a
2180 // list.
2181 if (IsSeqCst)
2182 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2183}
2184
Alexey Bataevb57056f2015-01-22 06:17:56 +00002185static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002186 bool IsSeqCst, bool IsPostfixUpdate,
2187 const Expr *X, const Expr *V, const Expr *E,
2188 const Expr *UE, bool IsXLHSInRHSPart,
2189 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002190 switch (Kind) {
2191 case OMPC_read:
2192 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2193 break;
2194 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002195 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2196 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002197 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002198 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002199 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2200 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002201 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002202 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2203 IsXLHSInRHSPart, Loc);
2204 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002205 case OMPC_if:
2206 case OMPC_final:
2207 case OMPC_num_threads:
2208 case OMPC_private:
2209 case OMPC_firstprivate:
2210 case OMPC_lastprivate:
2211 case OMPC_reduction:
2212 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002213 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002214 case OMPC_collapse:
2215 case OMPC_default:
2216 case OMPC_seq_cst:
2217 case OMPC_shared:
2218 case OMPC_linear:
2219 case OMPC_aligned:
2220 case OMPC_copyin:
2221 case OMPC_copyprivate:
2222 case OMPC_flush:
2223 case OMPC_proc_bind:
2224 case OMPC_schedule:
2225 case OMPC_ordered:
2226 case OMPC_nowait:
2227 case OMPC_untied:
2228 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002229 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002230 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002231 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002232 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002233 case OMPC_simd:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002234 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2235 }
2236}
2237
2238void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002239 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002240 OpenMPClauseKind Kind = OMPC_unknown;
2241 for (auto *C : S.clauses()) {
2242 // Find first clause (skip seq_cst clause, if it is first).
2243 if (C->getClauseKind() != OMPC_seq_cst) {
2244 Kind = C->getClauseKind();
2245 break;
2246 }
2247 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002248
2249 const auto *CS =
2250 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002251 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002252 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002253 }
2254 // Processing for statements under 'atomic capture'.
2255 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2256 for (const auto *C : Compound->body()) {
2257 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2258 enterFullExpression(EWC);
2259 }
2260 }
2261 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002262
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002263 LexicalScope Scope(*this, S.getSourceRange());
2264 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002265 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2266 S.getV(), S.getExpr(), S.getUpdateExpr(),
2267 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002268 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002269 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002270}
2271
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002272void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2273 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2274}
2275
Alexey Bataev13314bf2014-10-09 04:18:56 +00002276void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2277 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2278}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002279
2280void CodeGenFunction::EmitOMPCancellationPointDirective(
2281 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002282 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2283 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002284}
2285
Alexey Bataev80909872015-07-02 11:25:17 +00002286void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002287 const Expr *IfCond = nullptr;
2288 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2289 if (C->getNameModifier() == OMPD_unknown ||
2290 C->getNameModifier() == OMPD_cancel) {
2291 IfCond = C->getCondition();
2292 break;
2293 }
2294 }
2295 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002296 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002297}
2298
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002299CodeGenFunction::JumpDest
2300CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2301 if (Kind == OMPD_parallel || Kind == OMPD_task)
2302 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002303 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2304 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2305 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002306}
Michael Wong65f367f2015-07-21 13:44:28 +00002307
2308// Generate the instructions for '#pragma omp target data' directive.
2309void CodeGenFunction::EmitOMPTargetDataDirective(
2310 const OMPTargetDataDirective &S) {
2311
2312 // emit the code inside the construct for now
2313 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002314 CGM.getOpenMPRuntime().emitInlinedDirective(
2315 *this, OMPD_target_data,
2316 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002317}