blob: cf54d0ee4535bb8c5a6ee924e8a590235abebaa2 [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(
Samuel Antaobed3c462015-10-02 16:14:20 +000024 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars,
25 bool UseOnlyReferences) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000026 const RecordDecl *RD = S.getCapturedRecordDecl();
27 auto CurField = RD->field_begin();
28 auto CurCap = S.captures().begin();
29 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
30 E = S.capture_init_end();
31 I != E; ++I, ++CurField, ++CurCap) {
32 if (CurField->hasCapturedVLAType()) {
33 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000034 auto *Val = VLASizeMap[VAT->getSizeExpr()];
35 // If we need to use only references, create a temporary location for the
36 // size of the VAT.
37 if (UseOnlyReferences) {
38 LValue LV =
39 MakeAddrLValue(CreateMemTemp(CurField->getType(), "__vla_size_ref"),
40 CurField->getType());
41 EmitStoreThroughLValue(RValue::get(Val), LV);
42 Val = LV.getAddress().getPointer();
43 }
44 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000045 } else if (CurCap->capturesThis())
46 CapturedVars.push_back(CXXThisValue);
47 else
48 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
49 }
50}
51
52llvm::Function *
Samuel Antaobed3c462015-10-02 16:14:20 +000053CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
54 bool UseOnlyReferences) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000055 assert(
56 CapturedStmtInfo &&
57 "CapturedStmtInfo should be set when generating the captured function");
58 const CapturedDecl *CD = S.getCapturedDecl();
59 const RecordDecl *RD = S.getCapturedRecordDecl();
60 assert(CD->hasBody() && "missing CapturedDecl body");
61
62 // Build the argument list.
63 ASTContext &Ctx = CGM.getContext();
64 FunctionArgList Args;
65 Args.append(CD->param_begin(),
66 std::next(CD->param_begin(), CD->getContextParamPosition()));
67 auto I = S.captures().begin();
68 for (auto *FD : RD->fields()) {
69 QualType ArgType = FD->getType();
70 IdentifierInfo *II = nullptr;
71 VarDecl *CapVar = nullptr;
72 if (I->capturesVariable()) {
73 CapVar = I->getCapturedVar();
74 II = CapVar->getIdentifier();
75 } else if (I->capturesThis())
76 II = &getContext().Idents.get("this");
77 else {
78 assert(I->capturesVariableArrayType());
79 II = &getContext().Idents.get("vla");
Samuel Antaobed3c462015-10-02 16:14:20 +000080 if (UseOnlyReferences)
81 ArgType = getContext().getLValueReferenceType(
82 ArgType, /*SpelledAsLValue=*/false);
Alexey Bataev2377fe92015-09-10 08:12:02 +000083 }
84 if (ArgType->isVariablyModifiedType())
85 ArgType = getContext().getVariableArrayDecayedType(ArgType);
86 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
87 FD->getLocation(), II, ArgType));
88 ++I;
89 }
90 Args.append(
91 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
92 CD->param_end());
93
94 // Create the function declaration.
95 FunctionType::ExtInfo ExtInfo;
96 const CGFunctionInfo &FuncInfo =
97 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
98 /*IsVariadic=*/false);
99 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
100
101 llvm::Function *F = llvm::Function::Create(
102 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
103 CapturedStmtInfo->getHelperName(), &CGM.getModule());
104 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
105 if (CD->isNothrow())
106 F->addFnAttr(llvm::Attribute::NoUnwind);
107
108 // Generate the function.
109 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
110 CD->getBody()->getLocStart());
111 unsigned Cnt = CD->getContextParamPosition();
112 I = S.captures().begin();
113 for (auto *FD : RD->fields()) {
114 LValue ArgLVal =
115 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
116 AlignmentSource::Decl);
117 if (FD->hasCapturedVLAType()) {
Samuel Antaobed3c462015-10-02 16:14:20 +0000118 if (UseOnlyReferences)
119 ArgLVal = EmitLoadOfReferenceLValue(
120 ArgLVal.getAddress(), ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000121 auto *ExprArg =
122 EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
123 auto VAT = FD->getCapturedVLAType();
124 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
125 } else if (I->capturesVariable()) {
126 auto *Var = I->getCapturedVar();
127 QualType VarTy = Var->getType();
128 Address ArgAddr = ArgLVal.getAddress();
129 if (!VarTy->isReferenceType()) {
130 ArgAddr = EmitLoadOfReference(
131 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
132 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000133 setAddrOfLocalVar(
134 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000135 } else {
136 // If 'this' is captured, load it into CXXThisValue.
137 assert(I->capturesThis());
138 CXXThisValue =
139 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
140 }
141 ++Cnt, ++I;
142 }
143
144 PGO.assignRegionCounters(CD, F);
145 CapturedStmtInfo->EmitBody(*this, CD->getBody());
146 FinishFunction(CD->getBodyRBrace());
147
148 return F;
149}
150
Alexey Bataev9959db52014-05-06 10:08:46 +0000151//===----------------------------------------------------------------------===//
152// OpenMP Directive Emission
153//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000154void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000155 Address DestAddr, Address SrcAddr, QualType OriginalType,
156 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000157 // Perform element-by-element initialization.
158 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000159
160 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000161 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000162 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
163 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
164
165 auto SrcBegin = SrcAddr.getPointer();
166 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000167 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000168 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
169 // The basic structure here is a while-do loop.
170 auto BodyBB = createBasicBlock("omp.arraycpy.body");
171 auto DoneBB = createBasicBlock("omp.arraycpy.done");
172 auto IsEmpty =
173 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
174 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000175
Alexey Bataev420d45b2015-04-14 05:11:24 +0000176 // Enter the loop body, making that address the current address.
177 auto EntryBB = Builder.GetInsertBlock();
178 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000179
180 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
181
182 llvm::PHINode *SrcElementPHI =
183 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
184 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
185 Address SrcElementCurrent =
186 Address(SrcElementPHI,
187 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
188
189 llvm::PHINode *DestElementPHI =
190 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
191 DestElementPHI->addIncoming(DestBegin, EntryBB);
192 Address DestElementCurrent =
193 Address(DestElementPHI,
194 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000195
Alexey Bataev420d45b2015-04-14 05:11:24 +0000196 // Emit copy.
197 CopyGen(DestElementCurrent, SrcElementCurrent);
198
199 // Shift the address forward by one element.
200 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000201 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000202 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000203 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000204 // Check whether we've reached the end.
205 auto Done =
206 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
207 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000208 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
209 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000210
211 // Done.
212 EmitBlock(DoneBB, /*IsFinished=*/true);
213}
214
John McCall7f416cc2015-09-08 08:05:57 +0000215void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
216 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000217 const VarDecl *SrcVD, const Expr *Copy) {
218 if (OriginalType->isArrayType()) {
219 auto *BO = dyn_cast<BinaryOperator>(Copy);
220 if (BO && BO->getOpcode() == BO_Assign) {
221 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000222 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000223 } else {
224 // For arrays with complex element types perform element by element
225 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000226 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000227 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000228 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000229 // Working with the single array element, so have to remap
230 // destination and source variables to corresponding array
231 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000232 CodeGenFunction::OMPPrivateScope Remap(*this);
233 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000234 return DestElement;
235 });
236 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000237 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000238 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000239 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000240 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000241 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000242 } else {
243 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000244 CodeGenFunction::OMPPrivateScope Remap(*this);
245 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
246 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000247 (void)Remap.Privatize();
248 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000249 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000250 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000251}
252
Alexey Bataev69c62a92015-04-15 04:52:20 +0000253bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
254 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000255 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000256 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000257 auto IRef = C->varlist_begin();
258 auto InitsRef = C->inits().begin();
259 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000260 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000261 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
262 EmittedAsFirstprivate.insert(OrigVD);
263 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
264 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
265 bool IsRegistered;
266 DeclRefExpr DRE(
267 const_cast<VarDecl *>(OrigVD),
268 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
269 OrigVD) != nullptr,
270 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000271 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000272 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000273 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000274 // Emit VarDecl with copy init for arrays.
275 // Get the address of the original variable captured in current
276 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000277 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000278 auto Emission = EmitAutoVarAlloca(*VD);
279 auto *Init = VD->getInit();
280 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
281 // Perform simple memcpy.
282 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000283 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000284 } else {
285 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000286 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000287 [this, VDInit, Init](Address DestElement,
288 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000289 // Clean up any temporaries needed by the initialization.
290 RunCleanupsScope InitScope(*this);
291 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000292 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000293 EmitAnyExprToMem(Init, DestElement,
294 Init->getType().getQualifiers(),
295 /*IsInitializer*/ false);
296 LocalDeclMap.erase(VDInit);
297 });
298 }
299 EmitAutoVarCleanups(Emission);
300 return Emission.getAllocatedAddress();
301 });
302 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000303 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000304 // Emit private VarDecl with copy init.
305 // Remap temp VDInit variable to the address of the original
306 // variable
307 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000308 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000309 EmitDecl(*VD);
310 LocalDeclMap.erase(VDInit);
311 return GetAddrOfLocalVar(VD);
312 });
313 }
314 assert(IsRegistered &&
315 "firstprivate var already registered as private");
316 // Silence the warning about unused variable.
317 (void)IsRegistered;
318 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000319 ++IRef, ++InitsRef;
320 }
321 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000322 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000323}
324
Alexey Bataev03b340a2014-10-21 03:16:40 +0000325void CodeGenFunction::EmitOMPPrivateClause(
326 const OMPExecutableDirective &D,
327 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000328 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000329 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000330 auto IRef = C->varlist_begin();
331 for (auto IInit : C->private_copies()) {
332 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000333 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
334 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
335 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000336 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000337 // Emit private VarDecl with copy init.
338 EmitDecl(*VD);
339 return GetAddrOfLocalVar(VD);
340 });
341 assert(IsRegistered && "private var already registered as private");
342 // Silence the warning about unused variable.
343 (void)IsRegistered;
344 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000345 ++IRef;
346 }
347 }
348}
349
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000350bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
351 // threadprivate_var1 = master_threadprivate_var1;
352 // operator=(threadprivate_var2, master_threadprivate_var2);
353 // ...
354 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000355 llvm::DenseSet<const VarDecl *> CopiedVars;
356 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000357 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000358 auto IRef = C->varlist_begin();
359 auto ISrcRef = C->source_exprs().begin();
360 auto IDestRef = C->destination_exprs().begin();
361 for (auto *AssignOp : C->assignment_ops()) {
362 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000363 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000364 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000365
366 // Get the address of the master variable. If we are emitting code with
367 // TLS support, the address is passed from the master as field in the
368 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000369 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000370 if (getLangOpts().OpenMPUseTLS &&
371 getContext().getTargetInfo().isTLSSupported()) {
372 assert(CapturedStmtInfo->lookup(VD) &&
373 "Copyin threadprivates should have been captured!");
374 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
375 VK_LValue, (*IRef)->getExprLoc());
376 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000378 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000379 MasterAddr =
380 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
381 : CGM.GetAddrOfGlobal(VD),
382 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000383 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000384 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000385 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000386 if (CopiedVars.size() == 1) {
387 // At first check if current thread is a master thread. If it is, no
388 // need to copy data.
389 CopyBegin = createBasicBlock("copyin.not.master");
390 CopyEnd = createBasicBlock("copyin.not.master.end");
391 Builder.CreateCondBr(
392 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000393 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
394 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000395 CopyBegin, CopyEnd);
396 EmitBlock(CopyBegin);
397 }
398 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
399 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000400 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000401 }
402 ++IRef;
403 ++ISrcRef;
404 ++IDestRef;
405 }
406 }
407 if (CopyEnd) {
408 // Exit out of copying procedure for non-master thread.
409 EmitBlock(CopyEnd, /*IsFinished=*/true);
410 return true;
411 }
412 return false;
413}
414
Alexey Bataev38e89532015-04-16 04:54:05 +0000415bool CodeGenFunction::EmitOMPLastprivateClauseInit(
416 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000417 bool HasAtLeastOneLastprivate = false;
418 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000419 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000420 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000421 auto IRef = C->varlist_begin();
422 auto IDestRef = C->destination_exprs().begin();
423 for (auto *IInit : C->private_copies()) {
424 // Keep the address of the original variable for future update at the end
425 // of the loop.
426 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
427 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
428 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000429 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000430 DeclRefExpr DRE(
431 const_cast<VarDecl *>(OrigVD),
432 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
433 OrigVD) != nullptr,
434 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
435 return EmitLValue(&DRE).getAddress();
436 });
437 // Check if the variable is also a firstprivate: in this case IInit is
438 // not generated. Initialization of this variable will happen in codegen
439 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000440 if (IInit) {
441 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
442 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000443 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000444 // Emit private VarDecl with copy init.
445 EmitDecl(*VD);
446 return GetAddrOfLocalVar(VD);
447 });
448 assert(IsRegistered &&
449 "lastprivate var already registered as private");
450 (void)IsRegistered;
451 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000452 }
453 ++IRef, ++IDestRef;
454 }
455 }
456 return HasAtLeastOneLastprivate;
457}
458
459void CodeGenFunction::EmitOMPLastprivateClauseFinal(
460 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
461 // Emit following code:
462 // if (<IsLastIterCond>) {
463 // orig_var1 = private_orig_var1;
464 // ...
465 // orig_varn = private_orig_varn;
466 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000467 llvm::BasicBlock *ThenBB = nullptr;
468 llvm::BasicBlock *DoneBB = nullptr;
469 if (IsLastIterCond) {
470 ThenBB = createBasicBlock(".omp.lastprivate.then");
471 DoneBB = createBasicBlock(".omp.lastprivate.done");
472 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
473 EmitBlock(ThenBB);
474 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000475 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
476 const Expr *LastIterVal = nullptr;
477 const Expr *IVExpr = nullptr;
478 const Expr *IncExpr = nullptr;
479 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000480 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
481 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
482 LoopDirective->getUpperBoundVariable())
483 ->getDecl())
484 ->getAnyInitializer();
485 IVExpr = LoopDirective->getIterationVariable();
486 IncExpr = LoopDirective->getInc();
487 auto IUpdate = LoopDirective->updates().begin();
488 for (auto *E : LoopDirective->counters()) {
489 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
490 LoopCountersAndUpdates[D] = *IUpdate;
491 ++IUpdate;
492 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000493 }
494 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000495 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000496 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000497 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000498 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000499 auto IRef = C->varlist_begin();
500 auto ISrcRef = C->source_exprs().begin();
501 auto IDestRef = C->destination_exprs().begin();
502 for (auto *AssignOp : C->assignment_ops()) {
503 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000504 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000505 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
506 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
507 // If lastprivate variable is a loop control variable for loop-based
508 // directive, update its value before copyin back to original
509 // variable.
510 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000511 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000512 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
513 IVExpr->getType().getQualifiers(),
514 /*IsInitializer=*/false);
515 EmitIgnoredExpr(IncExpr);
516 FirstLCV = false;
517 }
518 EmitIgnoredExpr(UpExpr);
519 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000520 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
521 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
522 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000523 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000524 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000525 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
526 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000527 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000528 Address(Builder.CreateLoad(PrivateAddr),
529 getNaturalTypeAlignment(RefTy->getPointeeType()));
530 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000531 }
532 ++IRef;
533 ++ISrcRef;
534 ++IDestRef;
535 }
536 }
537 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000538 if (IsLastIterCond) {
539 EmitBlock(DoneBB, /*IsFinished=*/true);
540 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000541}
542
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000543void CodeGenFunction::EmitOMPReductionClauseInit(
544 const OMPExecutableDirective &D,
545 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000546 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000547 auto ILHS = C->lhs_exprs().begin();
548 auto IRHS = C->rhs_exprs().begin();
549 for (auto IRef : C->varlists()) {
550 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
551 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
552 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
553 // Store the address of the original variable associated with the LHS
554 // implicit variable.
John McCall7f416cc2015-09-08 08:05:57 +0000555 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000556 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
557 CapturedStmtInfo->lookup(OrigVD) != nullptr,
558 IRef->getType(), VK_LValue, IRef->getExprLoc());
559 return EmitLValue(&DRE).getAddress();
560 });
561 // Emit reduction copy.
562 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000563 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000564 // Emit private VarDecl with reduction init.
565 EmitDecl(*PrivateVD);
566 return GetAddrOfLocalVar(PrivateVD);
567 });
568 assert(IsRegistered && "private var already registered as private");
569 // Silence the warning about unused variable.
570 (void)IsRegistered;
571 ++ILHS, ++IRHS;
572 }
573 }
574}
575
576void CodeGenFunction::EmitOMPReductionClauseFinal(
577 const OMPExecutableDirective &D) {
578 llvm::SmallVector<const Expr *, 8> LHSExprs;
579 llvm::SmallVector<const Expr *, 8> RHSExprs;
580 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000581 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000582 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000583 HasAtLeastOneReduction = true;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000584 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
585 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
586 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
587 }
588 if (HasAtLeastOneReduction) {
589 // Emit nowait reduction if nowait clause is present or directive is a
590 // parallel directive (it always has implicit barrier).
591 CGM.getOpenMPRuntime().emitReduction(
592 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000594 isOpenMPParallelDirective(D.getDirectiveKind()) ||
595 D.getDirectiveKind() == OMPD_simd,
596 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000597 }
598}
599
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000600static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
601 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000602 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000603 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000604 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000605 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
606 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000607 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000608 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000609 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000610 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000611 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
612 /*IgnoreResultAssign*/ true);
613 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
614 CGF, NumThreads, NumThreadsClause->getLocStart());
615 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000616 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000617 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000618 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
619 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
620 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000621 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000622 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
623 if (C->getNameModifier() == OMPD_unknown ||
624 C->getNameModifier() == OMPD_parallel) {
625 IfCond = C->getCondition();
626 break;
627 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000628 }
629 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000630 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000631}
632
633void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
634 LexicalScope Scope(*this, S.getSourceRange());
635 // Emit parallel region as a standalone region.
636 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
637 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000638 bool Copyins = CGF.EmitOMPCopyinClause(S);
639 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
640 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000641 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000642 // initialization of firstprivate variables or propagation master's thread
643 // values of threadprivate variables to local instances of that variables
644 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000645 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
646 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
647 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000648 }
649 CGF.EmitOMPPrivateClause(S, PrivateScope);
650 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
651 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000652 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000653 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000654 // Emit implicit barrier at the end of the 'parallel' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000655 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
656 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
657 /*ForceSimpleCall=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000658 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000659 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000660}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000661
Alexey Bataev0f34da12015-07-02 04:17:07 +0000662void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
663 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000664 RunCleanupsScope BodyScope(*this);
665 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000666 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000667 EmitIgnoredExpr(I);
668 }
Alexander Musman3276a272015-03-21 10:12:56 +0000669 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000670 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000671 for (auto U : C->updates()) {
672 EmitIgnoredExpr(U);
673 }
674 }
675
Alexander Musmana5f070a2014-10-01 06:03:56 +0000676 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000677 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000678 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000679 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000680 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000681 // The end (updates/cleanups).
682 EmitBlock(Continue.getBlock());
683 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000684 // TODO: Update lastprivates if the SeparateIter flag is true.
685 // This will be implemented in a follow-up OMPLastprivateClause patch, but
686 // result should be still correct without it, as we do not make these
687 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000688}
689
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000690void CodeGenFunction::EmitOMPInnerLoop(
691 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
692 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000693 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
694 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000695 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000696
697 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000698 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000699 EmitBlock(CondBlock);
700 LoopStack.push(CondBlock);
701
702 // If there are any cleanups between here and the loop-exit scope,
703 // create a block to stage a loop exit along.
704 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000705 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000706 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000707
Alexander Musmand196ef22014-10-07 08:57:09 +0000708 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000709
Alexey Bataev2df54a02015-03-12 08:53:29 +0000710 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000711 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000712 if (ExitBlock != LoopExit.getBlock()) {
713 EmitBlock(ExitBlock);
714 EmitBranchThroughCleanup(LoopExit);
715 }
716
717 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000718 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000719
720 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000721 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000722 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
723
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000724 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000725
726 // Emit "IV = IV + 1" and a back-edge to the condition block.
727 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000728 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000729 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000730 BreakContinueStack.pop_back();
731 EmitBranch(CondBlock);
732 LoopStack.pop();
733 // Emit the fall-through block.
734 EmitBlock(LoopExit.getBlock());
735}
736
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000737void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000738 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000739 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000740 for (auto Init : C->inits()) {
741 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000742 auto *OrigVD = cast<VarDecl>(
743 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
744 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
745 CapturedStmtInfo->lookup(OrigVD) != nullptr,
746 VD->getInit()->getType(), VK_LValue,
747 VD->getInit()->getExprLoc());
748 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
749 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000750 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000751 /*capturedByInit=*/false);
752 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000753 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000754 // Emit the linear steps for the linear clauses.
755 // If a step is not constant, it is pre-calculated before the loop.
756 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
757 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000758 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000759 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000760 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000761 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000762 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000763}
764
765static void emitLinearClauseFinal(CodeGenFunction &CGF,
766 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000767 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000768 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000769 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000770 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000771 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
772 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000773 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000774 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000776 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000777 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000778 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +0000779 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000780 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000781 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000782 }
783 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000784}
785
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000786static void emitAlignedClause(CodeGenFunction &CGF,
787 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000788 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000789 unsigned ClauseAlignment = 0;
790 if (auto AlignmentExpr = Clause->getAlignment()) {
791 auto AlignmentCI =
792 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
793 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000794 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000795 for (auto E : Clause->varlists()) {
796 unsigned Alignment = ClauseAlignment;
797 if (Alignment == 0) {
798 // OpenMP [2.8.1, Description]
799 // If no optional parameter is specified, implementation-defined default
800 // alignments for SIMD instructions on the target platforms are assumed.
801 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000802 CGF.getContext()
803 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
804 E->getType()->getPointeeType()))
805 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000806 }
807 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
808 "alignment is not power of 2");
809 if (Alignment != 0) {
810 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
811 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
812 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000813 }
814 }
815}
816
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000817static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000818 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +0000819 ArrayRef<Expr *> Counters,
820 ArrayRef<Expr *> PrivateCounters) {
821 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000822 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +0000823 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
824 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000825 Address Addr = Address::invalid();
826 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000827 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +0000828 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000829 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +0000830 Addr = VarEmission.getAllocatedAddress();
831 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000832 });
John McCall7f416cc2015-09-08 08:05:57 +0000833 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +0000834 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000835 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000836}
837
Alexey Bataev62dbb972015-04-22 11:59:37 +0000838static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
839 const Expr *Cond, llvm::BasicBlock *TrueBlock,
840 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000841 {
842 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000843 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
844 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000845 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000846 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +0000847 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000848 CGF.EmitIgnoredExpr(I);
849 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000850 }
851 // Check that loop is executed at least one time.
852 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
853}
854
Alexander Musman3276a272015-03-21 10:12:56 +0000855static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000856emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000857 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000858 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000859 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +0000860 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000861 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
862 auto *PrivateVD =
863 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000864 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000865 // Emit private VarDecl with copy init.
866 CGF.EmitVarDecl(*PrivateVD);
867 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +0000868 });
869 assert(IsRegistered && "linear var already registered as private");
870 // Silence the warning about unused variable.
871 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000872 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +0000873 }
874 }
875}
876
Alexey Bataev45bfad52015-08-21 12:19:04 +0000877static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
878 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000879 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +0000880 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
881 /*ignoreResult=*/true);
882 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
883 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
884 // In presence of finite 'safelen', it may be unsafe to mark all
885 // the memory instructions parallel, because loop-carried
886 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000887 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
888 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000889 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
890 /*ignoreResult=*/true);
891 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000892 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000893 // In presence of finite 'safelen', it may be unsafe to mark all
894 // the memory instructions parallel, because loop-carried
895 // dependences of 'safelen' iterations are possible.
896 CGF.LoopStack.setParallel(false);
897 }
898}
899
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000900void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
901 // Walk clauses and process safelen/lastprivate.
902 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000903 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +0000904 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000905}
906
907void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
908 auto IC = D.counters().begin();
909 for (auto F : D.finals()) {
910 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000911 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000912 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
913 CapturedStmtInfo->lookup(OrigVD) != nullptr,
914 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000915 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000916 OMPPrivateScope VarScope(*this);
917 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000918 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000919 (void)VarScope.Privatize();
920 EmitIgnoredExpr(F);
921 }
922 ++IC;
923 }
924 emitLinearClauseFinal(*this, D);
925}
926
Alexander Musman515ad8c2014-05-22 08:54:05 +0000927void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000928 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000929 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000930 // for (IV in 0..LastIteration) BODY;
931 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000932 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000933 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000934
Alexey Bataev62dbb972015-04-22 11:59:37 +0000935 // Emit: if (PreCond) - begin.
936 // If the condition constant folds and can be elided, avoid emitting the
937 // whole loop.
938 bool CondConstant;
939 llvm::BasicBlock *ContBlock = nullptr;
940 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
941 if (!CondConstant)
942 return;
943 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000944 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
945 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000946 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
947 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000948 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000949 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000950 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000951
952 // Emit the loop iteration variable.
953 const Expr *IVExpr = S.getIterationVariable();
954 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
955 CGF.EmitVarDecl(*IVDecl);
956 CGF.EmitIgnoredExpr(S.getInit());
957
958 // Emit the iterations count variable.
959 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000960 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000961 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
962 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
963 // Emit calculation of the iterations count.
964 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000965 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000966
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000967 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000968
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000969 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000970 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000971 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000972 {
973 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000974 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
975 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000976 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000977 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000978 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000979 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000980 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +0000981 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
982 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000983 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +0000984 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +0000985 CGF.EmitStopPoint(&S);
986 },
987 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000988 // Emit final copy of the lastprivate variables at the end of loops.
989 if (HasLastprivateClause) {
990 CGF.EmitOMPLastprivateClauseFinal(S);
991 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000992 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000993 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000994 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000995 // Emit: if (PreCond) - end.
996 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000997 CGF.EmitBranch(ContBlock);
998 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000999 }
1000 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001001 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001002}
1003
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001004void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
1005 const OMPLoopDirective &S,
1006 OMPPrivateScope &LoopScope,
John McCall7f416cc2015-09-08 08:05:57 +00001007 bool Ordered, Address LB,
1008 Address UB, Address ST,
1009 Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001010 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001011
1012 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001013 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001014
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001015 assert((Ordered ||
1016 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001017 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001018
1019 // Emit outer loop.
1020 //
1021 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001022 // When schedule(dynamic,chunk_size) is specified, the iterations are
1023 // distributed to threads in the team in chunks as the threads request them.
1024 // Each thread executes a chunk of iterations, then requests another chunk,
1025 // until no chunks remain to be distributed. Each chunk contains chunk_size
1026 // iterations, except for the last chunk to be distributed, which may have
1027 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1028 //
1029 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1030 // to threads in the team in chunks as the executing threads request them.
1031 // Each thread executes a chunk of iterations, then requests another chunk,
1032 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1033 // each chunk is proportional to the number of unassigned iterations divided
1034 // by the number of threads in the team, decreasing to 1. For a chunk_size
1035 // with value k (greater than 1), the size of each chunk is determined in the
1036 // same way, with the restriction that the chunks do not contain fewer than k
1037 // iterations (except for the last chunk to be assigned, which may have fewer
1038 // than k iterations).
1039 //
1040 // When schedule(auto) is specified, the decision regarding scheduling is
1041 // delegated to the compiler and/or runtime system. The programmer gives the
1042 // implementation the freedom to choose any possible mapping of iterations to
1043 // threads in the team.
1044 //
1045 // When schedule(runtime) is specified, the decision regarding scheduling is
1046 // deferred until run time, and the schedule and chunk size are taken from the
1047 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1048 // implementation defined
1049 //
1050 // while(__kmpc_dispatch_next(&LB, &UB)) {
1051 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001052 // while (idx <= UB) { BODY; ++idx;
1053 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1054 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001055 // }
1056 //
1057 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001058 // When schedule(static, chunk_size) is specified, iterations are divided into
1059 // chunks of size chunk_size, and the chunks are assigned to the threads in
1060 // the team in a round-robin fashion in the order of the thread number.
1061 //
1062 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1063 // while (idx <= UB) { BODY; ++idx; } // inner loop
1064 // LB = LB + ST;
1065 // UB = UB + ST;
1066 // }
1067 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001068
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001069 const Expr *IVExpr = S.getIterationVariable();
1070 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1071 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1072
John McCall7f416cc2015-09-08 08:05:57 +00001073 if (DynamicOrOrdered) {
1074 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1075 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1076 IVSize, IVSigned, Ordered, UBVal, Chunk);
1077 } else {
1078 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1079 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1080 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001081
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001082 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1083
1084 // Start the loop with a block that tests the condition.
1085 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1086 EmitBlock(CondBlock);
1087 LoopStack.push(CondBlock);
1088
1089 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001090 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001091 // UB = min(UB, GlobalUB)
1092 EmitIgnoredExpr(S.getEnsureUpperBound());
1093 // IV = LB
1094 EmitIgnoredExpr(S.getInit());
1095 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001096 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001097 } else {
1098 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1099 IL, LB, UB, ST);
1100 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001101
1102 // If there are any cleanups between here and the loop-exit scope,
1103 // create a block to stage a loop exit along.
1104 auto ExitBlock = LoopExit.getBlock();
1105 if (LoopScope.requiresCleanups())
1106 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1107
1108 auto LoopBody = createBasicBlock("omp.dispatch.body");
1109 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1110 if (ExitBlock != LoopExit.getBlock()) {
1111 EmitBlock(ExitBlock);
1112 EmitBranchThroughCleanup(LoopExit);
1113 }
1114 EmitBlock(LoopBody);
1115
Alexander Musman92bdaab2015-03-12 13:37:50 +00001116 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1117 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001118 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001119 EmitIgnoredExpr(S.getInit());
1120
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001121 // Create a block for the increment.
1122 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1123 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1124
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001125 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1126 // with dynamic/guided scheduling and without ordered clause.
1127 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
1128 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
1129 ScheduleKind == OMPC_SCHEDULE_guided) &&
1130 !Ordered);
1131 } else {
1132 EmitOMPSimdInit(S);
1133 }
1134
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001135 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001136 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1137 [&S, LoopExit](CodeGenFunction &CGF) {
1138 CGF.EmitOMPLoopBody(S, LoopExit);
1139 CGF.EmitStopPoint(&S);
1140 },
1141 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1142 if (Ordered) {
1143 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1144 CGF, Loc, IVSize, IVSigned);
1145 }
1146 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001147
1148 EmitBlock(Continue.getBlock());
1149 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001150 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001151 // Emit "LB = LB + Stride", "UB = UB + Stride".
1152 EmitIgnoredExpr(S.getNextLowerBound());
1153 EmitIgnoredExpr(S.getNextUpperBound());
1154 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001155
1156 EmitBranch(CondBlock);
1157 LoopStack.pop();
1158 // Emit the fall-through block.
1159 EmitBlock(LoopExit.getBlock());
1160
1161 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001162 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001163 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001164}
1165
Alexander Musmanc6388682014-12-15 07:07:06 +00001166/// \brief Emit a helper variable and return corresponding lvalue.
1167static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1168 const DeclRefExpr *Helper) {
1169 auto VDecl = cast<VarDecl>(Helper->getDecl());
1170 CGF.EmitVarDecl(*VDecl);
1171 return CGF.EmitLValue(Helper);
1172}
1173
Alexey Bataev040d5402015-05-12 08:35:28 +00001174static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1175emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1176 bool OuterRegion) {
1177 // Detect the loop schedule kind and chunk.
1178 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1179 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001180 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001181 ScheduleKind = C->getScheduleKind();
1182 if (const auto *Ch = C->getChunkSize()) {
1183 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1184 if (OuterRegion) {
1185 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1186 CGF.EmitVarDecl(*ImpVar);
1187 CGF.EmitStoreThroughLValue(
1188 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001189 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1190 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001191 } else {
1192 Ch = ImpRef;
1193 }
1194 }
1195 if (!C->getHelperChunkSize() || !OuterRegion) {
1196 Chunk = CGF.EmitScalarExpr(Ch);
1197 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001198 S.getIterationVariable()->getType(),
1199 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001200 }
1201 }
1202 }
1203 return std::make_pair(Chunk, ScheduleKind);
1204}
1205
Alexey Bataev38e89532015-04-16 04:54:05 +00001206bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001207 // Emit the loop iteration variable.
1208 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1209 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1210 EmitVarDecl(*IVDecl);
1211
1212 // Emit the iterations count variable.
1213 // If it is not a variable, Sema decided to calculate iterations count on each
1214 // iteration (e.g., it is foldable into a constant).
1215 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1216 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1217 // Emit calculation of the iterations count.
1218 EmitIgnoredExpr(S.getCalcLastIteration());
1219 }
1220
1221 auto &RT = CGM.getOpenMPRuntime();
1222
Alexey Bataev38e89532015-04-16 04:54:05 +00001223 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001224 // Check pre-condition.
1225 {
1226 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001227 // If the condition constant folds and can be elided, avoid emitting the
1228 // whole loop.
1229 bool CondConstant;
1230 llvm::BasicBlock *ContBlock = nullptr;
1231 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1232 if (!CondConstant)
1233 return false;
1234 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001235 auto *ThenBlock = createBasicBlock("omp.precond.then");
1236 ContBlock = createBasicBlock("omp.precond.end");
1237 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001238 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001239 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001240 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001241 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001242
1243 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001244 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001245 // Emit 'then' code.
1246 {
1247 // Emit helper vars inits.
1248 LValue LB =
1249 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1250 LValue UB =
1251 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1252 LValue ST =
1253 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1254 LValue IL =
1255 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1256
1257 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001258 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1259 // Emit implicit barrier to synchronize threads and avoid data races on
1260 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001261 CGM.getOpenMPRuntime().emitBarrierCall(
1262 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1263 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001264 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001265 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001266 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001267 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001268 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1269 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001270 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001271 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001272
1273 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001274 llvm::Value *Chunk;
1275 OpenMPScheduleClauseKind ScheduleKind;
1276 auto ScheduleInfo =
1277 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1278 Chunk = ScheduleInfo.first;
1279 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001280 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1281 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001282 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001283 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001284 /* Chunked */ Chunk != nullptr) &&
1285 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001286 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1287 EmitOMPSimdInit(S);
1288 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001289 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1290 // When no chunk_size is specified, the iteration space is divided into
1291 // chunks that are approximately equal in size, and at most one chunk is
1292 // distributed to each thread. Note that the size of the chunks is
1293 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001294 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1295 IVSize, IVSigned, Ordered,
1296 IL.getAddress(), LB.getAddress(),
1297 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001298 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001299 // UB = min(UB, GlobalUB);
1300 EmitIgnoredExpr(S.getEnsureUpperBound());
1301 // IV = LB;
1302 EmitIgnoredExpr(S.getInit());
1303 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001304 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1305 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001306 [&S, LoopExit](CodeGenFunction &CGF) {
1307 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001308 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001309 },
1310 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001311 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001312 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001313 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001314 } else {
1315 // Emit the outer loop, which requests its work chunk [LB..UB] from
1316 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001317 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1318 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1319 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001320 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001321 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001322 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1323 if (HasLastprivateClause)
1324 EmitOMPLastprivateClauseFinal(
1325 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001326 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001327 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1328 EmitOMPSimdFinal(S);
1329 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001330 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001331 if (ContBlock) {
1332 EmitBranch(ContBlock);
1333 EmitBlock(ContBlock, true);
1334 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001335 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001336 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001337}
1338
1339void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001340 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001341 bool HasLastprivates = false;
1342 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1343 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1344 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001345 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1346 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001347
1348 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001349 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001350 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1351 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001352}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001353
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001354void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1355 LexicalScope Scope(*this, S.getSourceRange());
1356 bool HasLastprivates = false;
1357 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1358 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1359 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001360 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001361
1362 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001363 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1365 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001366}
1367
Alexey Bataev2df54a02015-03-12 08:53:29 +00001368static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1369 const Twine &Name,
1370 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001371 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001372 if (Init)
1373 CGF.EmitScalarInit(Init, LVal);
1374 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001375}
1376
Alexey Bataev0f34da12015-07-02 04:17:07 +00001377OpenMPDirectiveKind
1378CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001379 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1380 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1381 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001382 bool HasLastprivates = false;
1383 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001384 auto &C = CGF.CGM.getContext();
1385 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1386 // Emit helper vars inits.
1387 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1388 CGF.Builder.getInt32(0));
1389 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1390 LValue UB =
1391 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1392 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1393 CGF.Builder.getInt32(1));
1394 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1395 CGF.Builder.getInt32(0));
1396 // Loop counter.
1397 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1398 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001399 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001400 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001401 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001402 // Generate condition for loop.
1403 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1404 OK_Ordinary, S.getLocStart(),
1405 /*fpContractable=*/false);
1406 // Increment for loop counter.
1407 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1408 OK_Ordinary, S.getLocStart());
1409 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1410 // Iterate through all sections and emit a switch construct:
1411 // switch (IV) {
1412 // case 0:
1413 // <SectionStmt[0]>;
1414 // break;
1415 // ...
1416 // case <NumSection> - 1:
1417 // <SectionStmt[<NumSection> - 1]>;
1418 // break;
1419 // }
1420 // .omp.sections.exit:
1421 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1422 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1423 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1424 CS->size());
1425 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001426 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001427 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1428 CGF.EmitBlock(CaseBB);
1429 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001430 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001431 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001432 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001433 }
1434 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1435 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001436
1437 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1438 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1439 // Emit implicit barrier to synchronize threads and avoid data races on
1440 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001441 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1442 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1443 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001444 }
Alexey Bataev73870832015-04-27 04:12:12 +00001445 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001446 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001447 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001448 (void)LoopScope.Privatize();
1449
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001450 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001451 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001452 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001453 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1454 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001455 // UB = min(UB, GlobalUB);
1456 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1457 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1458 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1459 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1460 // IV = LB;
1461 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1462 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001463 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1464 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001465 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001466 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001467 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001468
1469 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1470 if (HasLastprivates)
1471 CGF.EmitOMPLastprivateClauseFinal(
1472 S, CGF.Builder.CreateIsNotNull(
1473 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001474 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001475
Alexey Bataev25e5b442015-09-15 12:52:43 +00001476 bool HasCancel = false;
1477 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1478 HasCancel = OSD->hasCancel();
1479 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1480 HasCancel = OPSD->hasCancel();
1481 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1482 HasCancel);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001483 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1484 // clause. Otherwise the barrier will be generated by the codegen for the
1485 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001486 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001487 // Emit implicit barrier to synchronize threads and avoid data races on
1488 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001489 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1490 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001491 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001492 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001493 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001494 // If only one section is found - no need to generate loop, emit as a single
1495 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001496 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001497 // No need to generate reductions for sections with single section region, we
1498 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001499 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001500 // No need to generate lastprivates for sections with single section region,
1501 // we can use original shared variable for all calculations with barrier at
1502 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001503 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001504 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1505 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1506 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001507 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001508 (void)SingleScope.Privatize();
1509
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001510 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001511 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001512 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1513 llvm::None, llvm::None, llvm::None,
1514 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001515 // Emit barrier for firstprivates, lastprivates or reductions only if
1516 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1517 // generated by the codegen for the directive.
1518 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001519 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001520 // Emit implicit barrier to synchronize threads and avoid data races on
1521 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001522 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown,
1523 /*EmitChecks=*/false,
1524 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001525 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001526 return OMPD_single;
1527}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001528
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001529void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1530 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001531 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001532 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001533 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001534 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001535 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001536}
1537
1538void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001539 LexicalScope Scope(*this, S.getSourceRange());
1540 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1541 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1542 CGF.EnsureInsertPoint();
1543 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001544 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1545 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001546}
1547
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001548void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001549 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001550 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001551 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001552 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001553 // Check if there are any 'copyprivate' clauses associated with this
1554 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001555 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001556 // Build a list of copyprivate variables along with helper expressions
1557 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001558 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001559 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001560 DestExprs.append(C->destination_exprs().begin(),
1561 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001562 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001563 AssignmentOps.append(C->assignment_ops().begin(),
1564 C->assignment_ops().end());
1565 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001566 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001567 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001568 bool HasFirstprivates;
1569 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1570 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1571 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001572 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001573 (void)SingleScope.Privatize();
1574
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001575 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1576 CGF.EnsureInsertPoint();
1577 };
1578 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001579 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001580 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001581 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1582 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001583 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001584 CopyprivateVars.empty()) {
1585 CGM.getOpenMPRuntime().emitBarrierCall(
1586 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001587 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001588 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001589}
1590
Alexey Bataev8d690652014-12-04 07:23:53 +00001591void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001592 LexicalScope Scope(*this, S.getSourceRange());
1593 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1594 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1595 CGF.EnsureInsertPoint();
1596 };
1597 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001598}
1599
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001600void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001601 LexicalScope Scope(*this, S.getSourceRange());
1602 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1603 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1604 CGF.EnsureInsertPoint();
1605 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001606 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001607 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001608}
1609
Alexey Bataev671605e2015-04-13 05:28:11 +00001610void CodeGenFunction::EmitOMPParallelForDirective(
1611 const OMPParallelForDirective &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());
Alexey Bataev040d5402015-05-12 08:35:28 +00001615 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001616 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 Bataev671605e2015-04-13 05:28:11 +00001624 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001625 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001626}
1627
Alexander Musmane4e893b2014-09-23 09:33:00 +00001628void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001629 const OMPParallelForSimdDirective &S) {
1630 // Emit directive as a combined directive that consists of two implicit
1631 // directives: 'parallel' with 'for' directive.
1632 LexicalScope Scope(*this, S.getSourceRange());
1633 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1634 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1635 CGF.EmitOMPWorksharingLoop(S);
1636 // Emit implicit barrier at the end of parallel region, but this barrier
1637 // is at the end of 'for' directive, so emit it as the implicit barrier for
1638 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001639 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1640 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1641 /*ForceSimpleCall=*/true);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001642 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001643 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001644}
1645
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001646void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001647 const OMPParallelSectionsDirective &S) {
1648 // Emit directive as a combined directive that consists of two implicit
1649 // directives: 'parallel' with 'sections' directive.
1650 LexicalScope Scope(*this, S.getSourceRange());
1651 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001652 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001653 // Emit implicit barrier at the end of parallel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001654 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1655 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1656 /*ForceSimpleCall=*/true);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001657 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001658 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001659}
1660
Alexey Bataev62b63b12015-03-10 07:28:44 +00001661void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1662 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001663 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001664 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1665 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1666 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001667 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001668 // The first function argument for tasks is a thread id, the second one is a
1669 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001670 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1671 // Get list of private variables.
1672 llvm::SmallVector<const Expr *, 8> PrivateVars;
1673 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001674 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001675 auto IRef = C->varlist_begin();
1676 for (auto *IInit : C->private_copies()) {
1677 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1678 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1679 PrivateVars.push_back(*IRef);
1680 PrivateCopies.push_back(IInit);
1681 }
1682 ++IRef;
1683 }
1684 }
1685 EmittedAsPrivate.clear();
1686 // Get list of firstprivate variables.
1687 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1688 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1689 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001690 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001691 auto IRef = C->varlist_begin();
1692 auto IElemInitRef = C->inits().begin();
1693 for (auto *IInit : C->private_copies()) {
1694 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1695 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1696 FirstprivateVars.push_back(*IRef);
1697 FirstprivateCopies.push_back(IInit);
1698 FirstprivateInits.push_back(*IElemInitRef);
1699 }
1700 ++IRef, ++IElemInitRef;
1701 }
1702 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001703 // Build list of dependences.
1704 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1705 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001706 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001707 for (auto *IRef : C->varlists()) {
1708 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1709 }
1710 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001711 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1712 CodeGenFunction &CGF) {
1713 // Set proper addresses for generated private copies.
1714 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1715 OMPPrivateScope Scope(CGF);
1716 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001717 auto *CopyFn = CGF.Builder.CreateLoad(
1718 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1719 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1720 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001721 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001722 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001723 PrivatePtrs;
1724 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1725 CallArgs.push_back(PrivatesPtr);
1726 for (auto *E : PrivateVars) {
1727 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001728 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001729 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1730 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001731 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001732 }
1733 for (auto *E : FirstprivateVars) {
1734 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001735 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001736 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1737 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001738 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001739 }
1740 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1741 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00001742 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
1743 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001744 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1745 }
1746 }
1747 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001748 if (*PartId) {
1749 // TODO: emit code for untied tasks.
1750 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001751 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001752 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001753 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1754 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001755 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001756 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001757 // Check if the task is final
1758 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001759 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001760 // If the condition constant folds and can be elided, try to avoid emitting
1761 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001762 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001763 bool CondConstant;
1764 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1765 Final.setInt(CondConstant);
1766 else
1767 Final.setPointer(EvaluateExprAsBool(Cond));
1768 } else {
1769 // By default the task is not final.
1770 Final.setInt(/*IntVal=*/false);
1771 }
1772 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001773 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001774 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1775 if (C->getNameModifier() == OMPD_unknown ||
1776 C->getNameModifier() == OMPD_task) {
1777 IfCond = C->getCondition();
1778 break;
1779 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001780 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001781 CGM.getOpenMPRuntime().emitTaskCall(
1782 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001783 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001784 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001785}
1786
Alexey Bataev9f797f32015-02-05 05:57:51 +00001787void CodeGenFunction::EmitOMPTaskyieldDirective(
1788 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001789 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001790}
1791
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001792void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001793 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001794}
1795
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001796void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1797 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001798}
1799
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001800void CodeGenFunction::EmitOMPTaskgroupDirective(
1801 const OMPTaskgroupDirective &S) {
1802 LexicalScope Scope(*this, S.getSourceRange());
1803 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1804 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1805 CGF.EnsureInsertPoint();
1806 };
1807 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1808}
1809
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001810void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001811 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001812 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001813 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1814 FlushClause->varlist_end());
1815 }
1816 return llvm::None;
1817 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001818}
1819
Alexey Bataev5f600d62015-09-29 03:48:57 +00001820static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
1821 const CapturedStmt *S) {
1822 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1823 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
1824 CGF.CapturedStmtInfo = &CapStmtInfo;
1825 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
1826 Fn->addFnAttr(llvm::Attribute::NoInline);
1827 return Fn;
1828}
1829
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001830void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1831 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00001832 auto *C = S.getSingleClause<OMPSIMDClause>();
1833 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
1834 if (C) {
1835 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1836 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1837 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1838 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
1839 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
1840 } else {
1841 CGF.EmitStmt(
1842 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1843 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001844 CGF.EnsureInsertPoint();
1845 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00001846 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001847}
1848
Alexey Bataevb57056f2015-01-22 06:17:56 +00001849static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001850 QualType SrcType, QualType DestType,
1851 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001852 assert(CGF.hasScalarEvaluationKind(DestType) &&
1853 "DestType must have scalar evaluation kind.");
1854 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1855 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001856 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
1857 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00001858 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001859 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001860}
1861
1862static CodeGenFunction::ComplexPairTy
1863convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001864 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001865 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1866 "DestType must have complex evaluation kind.");
1867 CodeGenFunction::ComplexPairTy ComplexVal;
1868 if (Val.isScalar()) {
1869 // Convert the input element to the element type of the complex.
1870 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001871 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
1872 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001873 ComplexVal = CodeGenFunction::ComplexPairTy(
1874 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1875 } else {
1876 assert(Val.isComplex() && "Must be a scalar or complex.");
1877 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1878 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1879 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001880 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001881 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001882 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001883 }
1884 return ComplexVal;
1885}
1886
Alexey Bataev5e018f92015-04-23 06:35:10 +00001887static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1888 LValue LVal, RValue RVal) {
1889 if (LVal.isGlobalReg()) {
1890 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1891 } else {
1892 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1893 : llvm::Monotonic,
1894 LVal.isVolatile(), /*IsInit=*/false);
1895 }
1896}
1897
1898static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001899 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001900 switch (CGF.getEvaluationKind(LVal.getType())) {
1901 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001902 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
1903 CGF, RVal, RValTy, LVal.getType(), Loc)),
1904 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001905 break;
1906 case TEK_Complex:
1907 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001908 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001909 /*isInit=*/false);
1910 break;
1911 case TEK_Aggregate:
1912 llvm_unreachable("Must be a scalar or complex.");
1913 }
1914}
1915
Alexey Bataevb57056f2015-01-22 06:17:56 +00001916static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1917 const Expr *X, const Expr *V,
1918 SourceLocation Loc) {
1919 // v = x;
1920 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1921 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1922 LValue XLValue = CGF.EmitLValue(X);
1923 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001924 RValue Res = XLValue.isGlobalReg()
1925 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1926 : CGF.EmitAtomicLoad(XLValue, Loc,
1927 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001928 : llvm::Monotonic,
1929 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001930 // OpenMP, 2.12.6, atomic Construct
1931 // Any atomic construct with a seq_cst clause forces the atomically
1932 // performed operation to include an implicit flush operation without a
1933 // list.
1934 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001935 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001936 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001937}
1938
Alexey Bataevb8329262015-02-27 06:33:30 +00001939static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1940 const Expr *X, const Expr *E,
1941 SourceLocation Loc) {
1942 // x = expr;
1943 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001944 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001945 // OpenMP, 2.12.6, atomic Construct
1946 // Any atomic construct with a seq_cst clause forces the atomically
1947 // performed operation to include an implicit flush operation without a
1948 // list.
1949 if (IsSeqCst)
1950 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1951}
1952
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001953static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1954 RValue Update,
1955 BinaryOperatorKind BO,
1956 llvm::AtomicOrdering AO,
1957 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001958 auto &Context = CGF.CGM.getContext();
1959 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001960 // expression is simple and atomic is allowed for the given type for the
1961 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001962 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001963 !Update.getScalarVal()->getType()->isIntegerTy() ||
1964 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1965 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00001966 X.getAddress().getElementType())) ||
1967 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001968 !Context.getTargetInfo().hasBuiltinAtomic(
1969 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001970 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001971
1972 llvm::AtomicRMWInst::BinOp RMWOp;
1973 switch (BO) {
1974 case BO_Add:
1975 RMWOp = llvm::AtomicRMWInst::Add;
1976 break;
1977 case BO_Sub:
1978 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001979 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001980 RMWOp = llvm::AtomicRMWInst::Sub;
1981 break;
1982 case BO_And:
1983 RMWOp = llvm::AtomicRMWInst::And;
1984 break;
1985 case BO_Or:
1986 RMWOp = llvm::AtomicRMWInst::Or;
1987 break;
1988 case BO_Xor:
1989 RMWOp = llvm::AtomicRMWInst::Xor;
1990 break;
1991 case BO_LT:
1992 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1993 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1994 : llvm::AtomicRMWInst::Max)
1995 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1996 : llvm::AtomicRMWInst::UMax);
1997 break;
1998 case BO_GT:
1999 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2000 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2001 : llvm::AtomicRMWInst::Min)
2002 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2003 : llvm::AtomicRMWInst::UMin);
2004 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002005 case BO_Assign:
2006 RMWOp = llvm::AtomicRMWInst::Xchg;
2007 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002008 case BO_Mul:
2009 case BO_Div:
2010 case BO_Rem:
2011 case BO_Shl:
2012 case BO_Shr:
2013 case BO_LAnd:
2014 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002015 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002016 case BO_PtrMemD:
2017 case BO_PtrMemI:
2018 case BO_LE:
2019 case BO_GE:
2020 case BO_EQ:
2021 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002022 case BO_AddAssign:
2023 case BO_SubAssign:
2024 case BO_AndAssign:
2025 case BO_OrAssign:
2026 case BO_XorAssign:
2027 case BO_MulAssign:
2028 case BO_DivAssign:
2029 case BO_RemAssign:
2030 case BO_ShlAssign:
2031 case BO_ShrAssign:
2032 case BO_Comma:
2033 llvm_unreachable("Unsupported atomic update operation");
2034 }
2035 auto *UpdateVal = Update.getScalarVal();
2036 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2037 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002038 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002039 X.getType()->hasSignedIntegerRepresentation());
2040 }
John McCall7f416cc2015-09-08 08:05:57 +00002041 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002042 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002043}
2044
Alexey Bataev5e018f92015-04-23 06:35:10 +00002045std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002046 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2047 llvm::AtomicOrdering AO, SourceLocation Loc,
2048 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2049 // Update expressions are allowed to have the following forms:
2050 // x binop= expr; -> xrval + expr;
2051 // x++, ++x -> xrval + 1;
2052 // x--, --x -> xrval - 1;
2053 // x = x binop expr; -> xrval binop expr
2054 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002055 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2056 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002057 if (X.isGlobalReg()) {
2058 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2059 // 'xrval'.
2060 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2061 } else {
2062 // Perform compare-and-swap procedure.
2063 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002064 }
2065 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002066 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002067}
2068
2069static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2070 const Expr *X, const Expr *E,
2071 const Expr *UE, bool IsXLHSInRHSPart,
2072 SourceLocation Loc) {
2073 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2074 "Update expr in 'atomic update' must be a binary operator.");
2075 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2076 // Update expressions are allowed to have the following forms:
2077 // x binop= expr; -> xrval + expr;
2078 // x++, ++x -> xrval + 1;
2079 // x--, --x -> xrval - 1;
2080 // x = x binop expr; -> xrval binop expr
2081 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002082 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002083 LValue XLValue = CGF.EmitLValue(X);
2084 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002085 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002086 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2087 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2088 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2089 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2090 auto Gen =
2091 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2092 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2093 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2094 return CGF.EmitAnyExpr(UE);
2095 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002096 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2097 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2098 // OpenMP, 2.12.6, atomic Construct
2099 // Any atomic construct with a seq_cst clause forces the atomically
2100 // performed operation to include an implicit flush operation without a
2101 // list.
2102 if (IsSeqCst)
2103 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2104}
2105
2106static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002107 QualType SourceType, QualType ResType,
2108 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002109 switch (CGF.getEvaluationKind(ResType)) {
2110 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002111 return RValue::get(
2112 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002113 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002114 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002115 return RValue::getComplex(Res.first, Res.second);
2116 }
2117 case TEK_Aggregate:
2118 break;
2119 }
2120 llvm_unreachable("Must be a scalar or complex.");
2121}
2122
2123static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2124 bool IsPostfixUpdate, const Expr *V,
2125 const Expr *X, const Expr *E,
2126 const Expr *UE, bool IsXLHSInRHSPart,
2127 SourceLocation Loc) {
2128 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2129 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2130 RValue NewVVal;
2131 LValue VLValue = CGF.EmitLValue(V);
2132 LValue XLValue = CGF.EmitLValue(X);
2133 RValue ExprRValue = CGF.EmitAnyExpr(E);
2134 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2135 QualType NewVValType;
2136 if (UE) {
2137 // 'x' is updated with some additional value.
2138 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2139 "Update expr in 'atomic capture' must be a binary operator.");
2140 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2141 // Update expressions are allowed to have the following forms:
2142 // x binop= expr; -> xrval + expr;
2143 // x++, ++x -> xrval + 1;
2144 // x--, --x -> xrval - 1;
2145 // x = x binop expr; -> xrval binop expr
2146 // x = expr Op x; - > expr binop xrval;
2147 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2148 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2149 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2150 NewVValType = XRValExpr->getType();
2151 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2152 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2153 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2154 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2155 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2156 RValue Res = CGF.EmitAnyExpr(UE);
2157 NewVVal = IsPostfixUpdate ? XRValue : Res;
2158 return Res;
2159 };
2160 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2161 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2162 if (Res.first) {
2163 // 'atomicrmw' instruction was generated.
2164 if (IsPostfixUpdate) {
2165 // Use old value from 'atomicrmw'.
2166 NewVVal = Res.second;
2167 } else {
2168 // 'atomicrmw' does not provide new value, so evaluate it using old
2169 // value of 'x'.
2170 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2171 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2172 NewVVal = CGF.EmitAnyExpr(UE);
2173 }
2174 }
2175 } else {
2176 // 'x' is simply rewritten with some 'expr'.
2177 NewVValType = X->getType().getNonReferenceType();
2178 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002179 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002180 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2181 NewVVal = XRValue;
2182 return ExprRValue;
2183 };
2184 // Try to perform atomicrmw xchg, otherwise simple exchange.
2185 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2186 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2187 Loc, Gen);
2188 if (Res.first) {
2189 // 'atomicrmw' instruction was generated.
2190 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2191 }
2192 }
2193 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002194 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002195 // OpenMP, 2.12.6, atomic Construct
2196 // Any atomic construct with a seq_cst clause forces the atomically
2197 // performed operation to include an implicit flush operation without a
2198 // list.
2199 if (IsSeqCst)
2200 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2201}
2202
Alexey Bataevb57056f2015-01-22 06:17:56 +00002203static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002204 bool IsSeqCst, bool IsPostfixUpdate,
2205 const Expr *X, const Expr *V, const Expr *E,
2206 const Expr *UE, bool IsXLHSInRHSPart,
2207 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002208 switch (Kind) {
2209 case OMPC_read:
2210 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2211 break;
2212 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002213 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2214 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002215 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002216 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002217 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2218 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002219 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002220 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2221 IsXLHSInRHSPart, Loc);
2222 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002223 case OMPC_if:
2224 case OMPC_final:
2225 case OMPC_num_threads:
2226 case OMPC_private:
2227 case OMPC_firstprivate:
2228 case OMPC_lastprivate:
2229 case OMPC_reduction:
2230 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002231 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002232 case OMPC_collapse:
2233 case OMPC_default:
2234 case OMPC_seq_cst:
2235 case OMPC_shared:
2236 case OMPC_linear:
2237 case OMPC_aligned:
2238 case OMPC_copyin:
2239 case OMPC_copyprivate:
2240 case OMPC_flush:
2241 case OMPC_proc_bind:
2242 case OMPC_schedule:
2243 case OMPC_ordered:
2244 case OMPC_nowait:
2245 case OMPC_untied:
2246 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002247 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002248 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002249 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002250 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002251 case OMPC_simd:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002252 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2253 }
2254}
2255
2256void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002257 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002258 OpenMPClauseKind Kind = OMPC_unknown;
2259 for (auto *C : S.clauses()) {
2260 // Find first clause (skip seq_cst clause, if it is first).
2261 if (C->getClauseKind() != OMPC_seq_cst) {
2262 Kind = C->getClauseKind();
2263 break;
2264 }
2265 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002266
2267 const auto *CS =
2268 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002269 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002270 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002271 }
2272 // Processing for statements under 'atomic capture'.
2273 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2274 for (const auto *C : Compound->body()) {
2275 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2276 enterFullExpression(EWC);
2277 }
2278 }
2279 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002281 LexicalScope Scope(*this, S.getSourceRange());
2282 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002283 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2284 S.getV(), S.getExpr(), S.getUpdateExpr(),
2285 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002286 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002287 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002288}
2289
Samuel Antaobed3c462015-10-02 16:14:20 +00002290void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2291 LexicalScope Scope(*this, S.getSourceRange());
2292 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2293
2294 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2295 GenerateOpenMPCapturedVars(CS, CapturedVars, /*UseOnlyReferences=*/true);
2296
2297 // Emit target region as a standalone region.
2298 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
2299 CGF.EmitStmt(CS.getCapturedStmt());
2300 };
2301
2302 // Obtain the target region outlined function.
2303 llvm::Value *Fn =
2304 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, CodeGen);
2305
2306 // Check if we have any if clause associated with the directive.
2307 const Expr *IfCond = nullptr;
2308
2309 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2310 IfCond = C->getCondition();
2311 }
2312
2313 // Check if we have any device clause associated with the directive.
2314 const Expr *Device = nullptr;
2315 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2316 Device = C->getDevice();
2317 }
2318
2319 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, IfCond, Device,
2320 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002321}
2322
Alexey Bataev13314bf2014-10-09 04:18:56 +00002323void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2324 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2325}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002326
2327void CodeGenFunction::EmitOMPCancellationPointDirective(
2328 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002329 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2330 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002331}
2332
Alexey Bataev80909872015-07-02 11:25:17 +00002333void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002334 const Expr *IfCond = nullptr;
2335 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2336 if (C->getNameModifier() == OMPD_unknown ||
2337 C->getNameModifier() == OMPD_cancel) {
2338 IfCond = C->getCondition();
2339 break;
2340 }
2341 }
2342 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002343 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002344}
2345
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002346CodeGenFunction::JumpDest
2347CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2348 if (Kind == OMPD_parallel || Kind == OMPD_task)
2349 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002350 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2351 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2352 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002353}
Michael Wong65f367f2015-07-21 13:44:28 +00002354
2355// Generate the instructions for '#pragma omp target data' directive.
2356void CodeGenFunction::EmitOMPTargetDataDirective(
2357 const OMPTargetDataDirective &S) {
2358
2359 // emit the code inside the construct for now
2360 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002361 CGM.getOpenMPRuntime().emitInlinedDirective(
2362 *this, OMPD_target_data,
2363 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002364}