blob: e0d1a5056c6ccd20e57dcd2253ce4175fe1c47a1 [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
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
21using namespace clang;
22using namespace CodeGen;
23
Alexey Bataev3392d762016-02-16 11:18:12 +000024namespace {
25/// Lexical scope for OpenMP executable constructs, that handles correct codegen
26/// for captured expressions.
27class OMPLexicalScope {
28 CodeGenFunction::LexicalScope Scope;
29 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30 for (const auto *C : S.clauses()) {
31 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
32 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
33 for (const auto *I : PreInit->decls())
34 CGF.EmitVarDecl(cast<VarDecl>(*I));
35 }
36 }
37 }
38 }
39
40 class PostUpdateCleanup final : public EHScopeStack::Cleanup {
41 const OMPExecutableDirective &S;
42
43 public:
44 PostUpdateCleanup(const OMPExecutableDirective &S) : S(S) {}
45
46 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
47 if (!CGF.HaveInsertPoint())
48 return;
49 (void)S;
50 // TODO: add cleanups for clauses that require post update.
51 }
52 };
53
54public:
55 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
56 : Scope(CGF, S.getSourceRange()) {
57 emitPreInitStmt(CGF, S);
58 CGF.EHStack.pushCleanup<PostUpdateCleanup>(NormalAndEHCleanup, S);
59 }
60};
61} // namespace
62
Alexey Bataev1189bd02016-01-26 12:20:39 +000063llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
64 auto &C = getContext();
65 llvm::Value *Size = nullptr;
66 auto SizeInChars = C.getTypeSizeInChars(Ty);
67 if (SizeInChars.isZero()) {
68 // getTypeSizeInChars() returns 0 for a VLA.
69 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
70 llvm::Value *ArraySize;
71 std::tie(ArraySize, Ty) = getVLASize(VAT);
72 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
73 }
74 SizeInChars = C.getTypeSizeInChars(Ty);
75 if (SizeInChars.isZero())
76 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
77 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
78 } else
79 Size = CGM.getSize(SizeInChars);
80 return Size;
81}
82
Alexey Bataev2377fe92015-09-10 08:12:02 +000083void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000084 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000085 const RecordDecl *RD = S.getCapturedRecordDecl();
86 auto CurField = RD->field_begin();
87 auto CurCap = S.captures().begin();
88 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
89 E = S.capture_init_end();
90 I != E; ++I, ++CurField, ++CurCap) {
91 if (CurField->hasCapturedVLAType()) {
92 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000093 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000094 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 } else if (CurCap->capturesThis())
96 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 else if (CurCap->capturesVariableByCopy())
98 CapturedVars.push_back(
99 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
100 else {
101 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000102 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000103 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000104 }
105}
106
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000107static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
108 StringRef Name, LValue AddrLV,
109 bool isReferenceType = false) {
110 ASTContext &Ctx = CGF.getContext();
111
112 auto *CastedPtr = CGF.EmitScalarConversion(
113 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
114 Ctx.getPointerType(DstType), SourceLocation());
115 auto TmpAddr =
116 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
117 .getAddress();
118
119 // If we are dealing with references we need to return the address of the
120 // reference instead of the reference of the value.
121 if (isReferenceType) {
122 QualType RefType = Ctx.getLValueReferenceType(DstType);
123 auto *RefVal = TmpAddr.getPointer();
124 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
125 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
126 CGF.EmitScalarInit(RefVal, TmpLVal);
127 }
128
129 return TmpAddr;
130}
131
Alexey Bataev2377fe92015-09-10 08:12:02 +0000132llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000133CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000134 assert(
135 CapturedStmtInfo &&
136 "CapturedStmtInfo should be set when generating the captured function");
137 const CapturedDecl *CD = S.getCapturedDecl();
138 const RecordDecl *RD = S.getCapturedRecordDecl();
139 assert(CD->hasBody() && "missing CapturedDecl body");
140
141 // Build the argument list.
142 ASTContext &Ctx = CGM.getContext();
143 FunctionArgList Args;
144 Args.append(CD->param_begin(),
145 std::next(CD->param_begin(), CD->getContextParamPosition()));
146 auto I = S.captures().begin();
147 for (auto *FD : RD->fields()) {
148 QualType ArgType = FD->getType();
149 IdentifierInfo *II = nullptr;
150 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000151
152 // If this is a capture by copy and the type is not a pointer, the outlined
153 // function argument type should be uintptr and the value properly casted to
154 // uintptr. This is necessary given that the runtime library is only able to
155 // deal with pointers. We can pass in the same way the VLA type sizes to the
156 // outlined function.
157 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
158 I->capturesVariableArrayType())
159 ArgType = Ctx.getUIntPtrType();
160
161 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000162 CapVar = I->getCapturedVar();
163 II = CapVar->getIdentifier();
164 } else if (I->capturesThis())
165 II = &getContext().Idents.get("this");
166 else {
167 assert(I->capturesVariableArrayType());
168 II = &getContext().Idents.get("vla");
169 }
170 if (ArgType->isVariablyModifiedType())
171 ArgType = getContext().getVariableArrayDecayedType(ArgType);
172 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
173 FD->getLocation(), II, ArgType));
174 ++I;
175 }
176 Args.append(
177 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
178 CD->param_end());
179
180 // Create the function declaration.
181 FunctionType::ExtInfo ExtInfo;
182 const CGFunctionInfo &FuncInfo =
183 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
184 /*IsVariadic=*/false);
185 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
186
187 llvm::Function *F = llvm::Function::Create(
188 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
189 CapturedStmtInfo->getHelperName(), &CGM.getModule());
190 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
191 if (CD->isNothrow())
192 F->addFnAttr(llvm::Attribute::NoUnwind);
193
194 // Generate the function.
195 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
196 CD->getBody()->getLocStart());
197 unsigned Cnt = CD->getContextParamPosition();
198 I = S.captures().begin();
199 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 // If we are capturing a pointer by copy we don't need to do anything, just
201 // use the value that we get from the arguments.
202 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
203 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
204 ++Cnt, ++I;
205 continue;
206 }
207
Alexey Bataev2377fe92015-09-10 08:12:02 +0000208 LValue ArgLVal =
209 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
210 AlignmentSource::Decl);
211 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000212 LValue CastedArgLVal =
213 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
214 Args[Cnt]->getName(), ArgLVal),
215 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000216 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000217 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000218 auto VAT = FD->getCapturedVLAType();
219 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
220 } else if (I->capturesVariable()) {
221 auto *Var = I->getCapturedVar();
222 QualType VarTy = Var->getType();
223 Address ArgAddr = ArgLVal.getAddress();
224 if (!VarTy->isReferenceType()) {
225 ArgAddr = EmitLoadOfReference(
226 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
227 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000228 setAddrOfLocalVar(
229 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 } else if (I->capturesVariableByCopy()) {
231 assert(!FD->getType()->isAnyPointerType() &&
232 "Not expecting a captured pointer.");
233 auto *Var = I->getCapturedVar();
234 QualType VarTy = Var->getType();
235 setAddrOfLocalVar(I->getCapturedVar(),
236 castValueFromUintptr(*this, FD->getType(),
237 Args[Cnt]->getName(), ArgLVal,
238 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000239 } else {
240 // If 'this' is captured, load it into CXXThisValue.
241 assert(I->capturesThis());
242 CXXThisValue =
243 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
244 }
245 ++Cnt, ++I;
246 }
247
Serge Pavlov3a561452015-12-06 14:32:39 +0000248 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000249 CapturedStmtInfo->EmitBody(*this, CD->getBody());
250 FinishFunction(CD->getBodyRBrace());
251
252 return F;
253}
254
Alexey Bataev9959db52014-05-06 10:08:46 +0000255//===----------------------------------------------------------------------===//
256// OpenMP Directive Emission
257//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000258void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000259 Address DestAddr, Address SrcAddr, QualType OriginalType,
260 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000261 // Perform element-by-element initialization.
262 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000263
264 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000265 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000266 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
267 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
268
269 auto SrcBegin = SrcAddr.getPointer();
270 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000271 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000272 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
273 // The basic structure here is a while-do loop.
274 auto BodyBB = createBasicBlock("omp.arraycpy.body");
275 auto DoneBB = createBasicBlock("omp.arraycpy.done");
276 auto IsEmpty =
277 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
278 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000279
Alexey Bataev420d45b2015-04-14 05:11:24 +0000280 // Enter the loop body, making that address the current address.
281 auto EntryBB = Builder.GetInsertBlock();
282 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000283
284 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
285
286 llvm::PHINode *SrcElementPHI =
287 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
288 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
289 Address SrcElementCurrent =
290 Address(SrcElementPHI,
291 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
292
293 llvm::PHINode *DestElementPHI =
294 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
295 DestElementPHI->addIncoming(DestBegin, EntryBB);
296 Address DestElementCurrent =
297 Address(DestElementPHI,
298 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000299
Alexey Bataev420d45b2015-04-14 05:11:24 +0000300 // Emit copy.
301 CopyGen(DestElementCurrent, SrcElementCurrent);
302
303 // Shift the address forward by one element.
304 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000305 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000306 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000307 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000308 // Check whether we've reached the end.
309 auto Done =
310 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
311 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000312 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
313 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000314
315 // Done.
316 EmitBlock(DoneBB, /*IsFinished=*/true);
317}
318
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000319/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000320/// \param DestAddr Address of the array.
321/// \param Type Type of array.
322/// \param Init Initial expression of array.
323static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
324 QualType Type, const Expr *Init) {
325 // Perform element-by-element initialization.
326 QualType ElementTy;
327
328 // Drill down to the base element type on both arrays.
329 auto ArrayTy = Type->getAsArrayTypeUnsafe();
330 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
331 DestAddr =
332 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
333
334 auto DestBegin = DestAddr.getPointer();
335 // Cast from pointer to array type to pointer to single element.
336 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
337 // The basic structure here is a while-do loop.
338 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
339 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
340 auto IsEmpty =
341 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
342 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
343
344 // Enter the loop body, making that address the current address.
345 auto EntryBB = CGF.Builder.GetInsertBlock();
346 CGF.EmitBlock(BodyBB);
347
348 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
349
350 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
351 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
352 DestElementPHI->addIncoming(DestBegin, EntryBB);
353 Address DestElementCurrent =
354 Address(DestElementPHI,
355 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
356
357 // Emit copy.
358 {
359 CodeGenFunction::RunCleanupsScope InitScope(CGF);
360 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
361 /*IsInitializer=*/false);
362 }
363
364 // Shift the address forward by one element.
365 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
366 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
367 // Check whether we've reached the end.
368 auto Done =
369 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
370 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
371 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
372
373 // Done.
374 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
375}
376
John McCall7f416cc2015-09-08 08:05:57 +0000377void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
378 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000379 const VarDecl *SrcVD, const Expr *Copy) {
380 if (OriginalType->isArrayType()) {
381 auto *BO = dyn_cast<BinaryOperator>(Copy);
382 if (BO && BO->getOpcode() == BO_Assign) {
383 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000384 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000385 } else {
386 // For arrays with complex element types perform element by element
387 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000388 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000389 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000390 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 // Working with the single array element, so have to remap
392 // destination and source variables to corresponding array
393 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000394 CodeGenFunction::OMPPrivateScope Remap(*this);
395 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000396 return DestElement;
397 });
398 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000399 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000400 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000401 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000402 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000403 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 } else {
405 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000406 CodeGenFunction::OMPPrivateScope Remap(*this);
407 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
408 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000409 (void)Remap.Privatize();
410 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000411 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000412 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000413}
414
Alexey Bataev69c62a92015-04-15 04:52:20 +0000415bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
416 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000417 if (!HaveInsertPoint())
418 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000419 bool FirstprivateIsLastprivate = false;
420 llvm::DenseSet<const VarDecl *> Lastprivates;
421 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
422 for (const auto *D : C->varlists())
423 Lastprivates.insert(
424 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
425 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000426 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000427 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000428 auto IRef = C->varlist_begin();
429 auto InitsRef = C->inits().begin();
430 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000431 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000432 FirstprivateIsLastprivate =
433 FirstprivateIsLastprivate ||
434 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
435 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000436 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
437 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
438 bool IsRegistered;
439 DeclRefExpr DRE(
440 const_cast<VarDecl *>(OrigVD),
441 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
442 OrigVD) != nullptr,
443 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000444 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000445 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000446 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000447 // Emit VarDecl with copy init for arrays.
448 // Get the address of the original variable captured in current
449 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000450 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000451 auto Emission = EmitAutoVarAlloca(*VD);
452 auto *Init = VD->getInit();
453 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
454 // Perform simple memcpy.
455 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000456 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 } else {
458 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000459 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000460 [this, VDInit, Init](Address DestElement,
461 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000462 // Clean up any temporaries needed by the initialization.
463 RunCleanupsScope InitScope(*this);
464 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000465 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000466 EmitAnyExprToMem(Init, DestElement,
467 Init->getType().getQualifiers(),
468 /*IsInitializer*/ false);
469 LocalDeclMap.erase(VDInit);
470 });
471 }
472 EmitAutoVarCleanups(Emission);
473 return Emission.getAllocatedAddress();
474 });
475 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000476 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 // Emit private VarDecl with copy init.
478 // Remap temp VDInit variable to the address of the original
479 // variable
480 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000481 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000482 EmitDecl(*VD);
483 LocalDeclMap.erase(VDInit);
484 return GetAddrOfLocalVar(VD);
485 });
486 }
487 assert(IsRegistered &&
488 "firstprivate var already registered as private");
489 // Silence the warning about unused variable.
490 (void)IsRegistered;
491 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492 ++IRef, ++InitsRef;
493 }
494 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000495 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000496}
497
Alexey Bataev03b340a2014-10-21 03:16:40 +0000498void CodeGenFunction::EmitOMPPrivateClause(
499 const OMPExecutableDirective &D,
500 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000501 if (!HaveInsertPoint())
502 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000503 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000504 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000505 auto IRef = C->varlist_begin();
506 for (auto IInit : C->private_copies()) {
507 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
509 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
510 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000511 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000512 // Emit private VarDecl with copy init.
513 EmitDecl(*VD);
514 return GetAddrOfLocalVar(VD);
515 });
516 assert(IsRegistered && "private var already registered as private");
517 // Silence the warning about unused variable.
518 (void)IsRegistered;
519 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000520 ++IRef;
521 }
522 }
523}
524
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000525bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000526 if (!HaveInsertPoint())
527 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 // threadprivate_var1 = master_threadprivate_var1;
529 // operator=(threadprivate_var2, master_threadprivate_var2);
530 // ...
531 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000532 llvm::DenseSet<const VarDecl *> CopiedVars;
533 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000534 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000535 auto IRef = C->varlist_begin();
536 auto ISrcRef = C->source_exprs().begin();
537 auto IDestRef = C->destination_exprs().begin();
538 for (auto *AssignOp : C->assignment_ops()) {
539 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000540 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000541 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 // Get the address of the master variable. If we are emitting code with
543 // TLS support, the address is passed from the master as field in the
544 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000545 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000546 if (getLangOpts().OpenMPUseTLS &&
547 getContext().getTargetInfo().isTLSSupported()) {
548 assert(CapturedStmtInfo->lookup(VD) &&
549 "Copyin threadprivates should have been captured!");
550 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
551 VK_LValue, (*IRef)->getExprLoc());
552 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000553 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000554 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000555 MasterAddr =
556 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
557 : CGM.GetAddrOfGlobal(VD),
558 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000559 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000560 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000561 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000562 if (CopiedVars.size() == 1) {
563 // At first check if current thread is a master thread. If it is, no
564 // need to copy data.
565 CopyBegin = createBasicBlock("copyin.not.master");
566 CopyEnd = createBasicBlock("copyin.not.master.end");
567 Builder.CreateCondBr(
568 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000569 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
570 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000571 CopyBegin, CopyEnd);
572 EmitBlock(CopyBegin);
573 }
574 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
575 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000576 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000577 }
578 ++IRef;
579 ++ISrcRef;
580 ++IDestRef;
581 }
582 }
583 if (CopyEnd) {
584 // Exit out of copying procedure for non-master thread.
585 EmitBlock(CopyEnd, /*IsFinished=*/true);
586 return true;
587 }
588 return false;
589}
590
Alexey Bataev38e89532015-04-16 04:54:05 +0000591bool CodeGenFunction::EmitOMPLastprivateClauseInit(
592 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000593 if (!HaveInsertPoint())
594 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 bool HasAtLeastOneLastprivate = false;
596 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000597 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000598 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000599 auto IRef = C->varlist_begin();
600 auto IDestRef = C->destination_exprs().begin();
601 for (auto *IInit : C->private_copies()) {
602 // Keep the address of the original variable for future update at the end
603 // of the loop.
604 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
605 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
606 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000607 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000608 DeclRefExpr DRE(
609 const_cast<VarDecl *>(OrigVD),
610 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
611 OrigVD) != nullptr,
612 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
613 return EmitLValue(&DRE).getAddress();
614 });
615 // Check if the variable is also a firstprivate: in this case IInit is
616 // not generated. Initialization of this variable will happen in codegen
617 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 if (IInit) {
619 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
620 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000621 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000622 // Emit private VarDecl with copy init.
623 EmitDecl(*VD);
624 return GetAddrOfLocalVar(VD);
625 });
626 assert(IsRegistered &&
627 "lastprivate var already registered as private");
628 (void)IsRegistered;
629 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000630 }
631 ++IRef, ++IDestRef;
632 }
633 }
634 return HasAtLeastOneLastprivate;
635}
636
637void CodeGenFunction::EmitOMPLastprivateClauseFinal(
638 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000639 if (!HaveInsertPoint())
640 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000641 // Emit following code:
642 // if (<IsLastIterCond>) {
643 // orig_var1 = private_orig_var1;
644 // ...
645 // orig_varn = private_orig_varn;
646 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000647 llvm::BasicBlock *ThenBB = nullptr;
648 llvm::BasicBlock *DoneBB = nullptr;
649 if (IsLastIterCond) {
650 ThenBB = createBasicBlock(".omp.lastprivate.then");
651 DoneBB = createBasicBlock(".omp.lastprivate.done");
652 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
653 EmitBlock(ThenBB);
654 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000655 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
656 const Expr *LastIterVal = nullptr;
657 const Expr *IVExpr = nullptr;
658 const Expr *IncExpr = nullptr;
659 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000660 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
661 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
662 LoopDirective->getUpperBoundVariable())
663 ->getDecl())
664 ->getAnyInitializer();
665 IVExpr = LoopDirective->getIterationVariable();
666 IncExpr = LoopDirective->getInc();
667 auto IUpdate = LoopDirective->updates().begin();
668 for (auto *E : LoopDirective->counters()) {
669 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
670 LoopCountersAndUpdates[D] = *IUpdate;
671 ++IUpdate;
672 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000673 }
674 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000675 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000676 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000677 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000678 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000679 auto IRef = C->varlist_begin();
680 auto ISrcRef = C->source_exprs().begin();
681 auto IDestRef = C->destination_exprs().begin();
682 for (auto *AssignOp : C->assignment_ops()) {
683 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000684 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000685 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
686 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
687 // If lastprivate variable is a loop control variable for loop-based
688 // directive, update its value before copyin back to original
689 // variable.
690 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000691 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000692 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
693 IVExpr->getType().getQualifiers(),
694 /*IsInitializer=*/false);
695 EmitIgnoredExpr(IncExpr);
696 FirstLCV = false;
697 }
698 EmitIgnoredExpr(UpExpr);
699 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000700 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
701 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
702 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000703 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000704 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000705 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
706 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000707 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000708 Address(Builder.CreateLoad(PrivateAddr),
709 getNaturalTypeAlignment(RefTy->getPointeeType()));
710 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000711 }
712 ++IRef;
713 ++ISrcRef;
714 ++IDestRef;
715 }
716 }
717 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000718 if (IsLastIterCond) {
719 EmitBlock(DoneBB, /*IsFinished=*/true);
720 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000721}
722
Alexey Bataev31300ed2016-02-04 11:27:03 +0000723static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
724 LValue BaseLV, llvm::Value *Addr) {
725 Address Tmp = Address::invalid();
726 Address TopTmp = Address::invalid();
727 Address MostTopTmp = Address::invalid();
728 BaseTy = BaseTy.getNonReferenceType();
729 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
730 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
731 Tmp = CGF.CreateMemTemp(BaseTy);
732 if (TopTmp.isValid())
733 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
734 else
735 MostTopTmp = Tmp;
736 TopTmp = Tmp;
737 BaseTy = BaseTy->getPointeeType();
738 }
739 llvm::Type *Ty = BaseLV.getPointer()->getType();
740 if (Tmp.isValid())
741 Ty = Tmp.getElementType();
742 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
743 if (Tmp.isValid()) {
744 CGF.Builder.CreateStore(Addr, Tmp);
745 return MostTopTmp;
746 }
747 return Address(Addr, BaseLV.getAlignment());
748}
749
750static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
751 LValue BaseLV) {
752 BaseTy = BaseTy.getNonReferenceType();
753 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
754 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
755 if (auto *PtrTy = BaseTy->getAs<PointerType>())
756 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
757 else {
758 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
759 BaseTy->castAs<ReferenceType>());
760 }
761 BaseTy = BaseTy->getPointeeType();
762 }
763 return CGF.MakeAddrLValue(
764 Address(
765 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
766 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
767 BaseLV.getAlignment()),
768 BaseLV.getType(), BaseLV.getAlignmentSource());
769}
770
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000771void CodeGenFunction::EmitOMPReductionClauseInit(
772 const OMPExecutableDirective &D,
773 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000774 if (!HaveInsertPoint())
775 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000776 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000777 auto ILHS = C->lhs_exprs().begin();
778 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000779 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000780 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000781 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000782 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
783 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
784 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
785 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
786 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
787 Base = TempOASE->getBase()->IgnoreParenImpCasts();
788 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
789 Base = TempASE->getBase()->IgnoreParenImpCasts();
790 auto *DE = cast<DeclRefExpr>(Base);
791 auto *OrigVD = cast<VarDecl>(DE->getDecl());
792 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
793 auto OASELValueUB =
794 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
795 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000796 LValue BaseLValue =
797 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
798 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000799 // Store the address of the original variable associated with the LHS
800 // implicit variable.
801 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
802 return OASELValueLB.getAddress();
803 });
804 // Emit reduction copy.
805 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000806 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
807 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000808 // Emit VarDecl with copy init for arrays.
809 // Get the address of the original variable captured in current
810 // captured region.
811 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
812 OASELValueLB.getPointer());
813 Size = Builder.CreateNUWAdd(
814 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
815 CodeGenFunction::OpaqueValueMapping OpaqueMap(
816 *this, cast<OpaqueValueExpr>(
817 getContext()
818 .getAsVariableArrayType(PrivateVD->getType())
819 ->getSizeExpr()),
820 RValue::get(Size));
821 EmitVariablyModifiedType(PrivateVD->getType());
822 auto Emission = EmitAutoVarAlloca(*PrivateVD);
823 auto Addr = Emission.getAllocatedAddress();
824 auto *Init = PrivateVD->getInit();
825 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
826 EmitAutoVarCleanups(Emission);
827 // Emit private VarDecl with reduction init.
828 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
829 OASELValueLB.getPointer());
830 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000831 return castToBase(*this, OrigVD->getType(),
832 OASELValueLB.getType(), OriginalBaseLValue,
833 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000834 });
835 assert(IsRegistered && "private var already registered as private");
836 // Silence the warning about unused variable.
837 (void)IsRegistered;
838 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
839 return GetAddrOfLocalVar(PrivateVD);
840 });
841 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
842 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
843 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
844 Base = TempASE->getBase()->IgnoreParenImpCasts();
845 auto *DE = cast<DeclRefExpr>(Base);
846 auto *OrigVD = cast<VarDecl>(DE->getDecl());
847 auto ASELValue = EmitLValue(ASE);
848 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000849 LValue BaseLValue = loadToBegin(
850 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000851 // Store the address of the original variable associated with the LHS
852 // implicit variable.
853 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
854 return ASELValue.getAddress();
855 });
856 // Emit reduction copy.
857 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000858 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 OriginalBaseLValue]() -> Address {
860 // Emit private VarDecl with reduction init.
861 EmitDecl(*PrivateVD);
862 auto Addr = GetAddrOfLocalVar(PrivateVD);
863 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
864 ASELValue.getPointer());
865 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000866 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
867 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000868 });
869 assert(IsRegistered && "private var already registered as private");
870 // Silence the warning about unused variable.
871 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000872 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
873 return Builder.CreateElementBitCast(
874 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
875 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000876 });
877 } else {
878 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000879 QualType Type = PrivateVD->getType();
880 if (getContext().getAsArrayType(Type)) {
881 // Store the address of the original variable associated with the LHS
882 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000883 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
884 CapturedStmtInfo->lookup(OrigVD) != nullptr,
885 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000886 Address OriginalAddr = EmitLValue(&DRE).getAddress();
887 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
888 LHSVD]() -> Address {
889 return Builder.CreateElementBitCast(
890 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
891 "lhs.begin");
892 });
893 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
894 if (Type->isVariablyModifiedType()) {
895 CodeGenFunction::OpaqueValueMapping OpaqueMap(
896 *this, cast<OpaqueValueExpr>(
897 getContext()
898 .getAsVariableArrayType(PrivateVD->getType())
899 ->getSizeExpr()),
900 RValue::get(
901 getTypeSize(OrigVD->getType().getNonReferenceType())));
902 EmitVariablyModifiedType(Type);
903 }
904 auto Emission = EmitAutoVarAlloca(*PrivateVD);
905 auto Addr = Emission.getAllocatedAddress();
906 auto *Init = PrivateVD->getInit();
907 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
908 EmitAutoVarCleanups(Emission);
909 return Emission.getAllocatedAddress();
910 });
911 assert(IsRegistered && "private var already registered as private");
912 // Silence the warning about unused variable.
913 (void)IsRegistered;
914 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
915 return Builder.CreateElementBitCast(
916 GetAddrOfLocalVar(PrivateVD),
917 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
918 });
919 } else {
920 // Store the address of the original variable associated with the LHS
921 // implicit variable.
922 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
923 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
924 CapturedStmtInfo->lookup(OrigVD) != nullptr,
925 IRef->getType(), VK_LValue, IRef->getExprLoc());
926 return EmitLValue(&DRE).getAddress();
927 });
928 // Emit reduction copy.
929 bool IsRegistered =
930 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
931 // Emit private VarDecl with reduction init.
932 EmitDecl(*PrivateVD);
933 return GetAddrOfLocalVar(PrivateVD);
934 });
935 assert(IsRegistered && "private var already registered as private");
936 // Silence the warning about unused variable.
937 (void)IsRegistered;
938 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
939 return GetAddrOfLocalVar(PrivateVD);
940 });
941 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 }
943 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000944 }
945 }
946}
947
948void CodeGenFunction::EmitOMPReductionClauseFinal(
949 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000950 if (!HaveInsertPoint())
951 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000952 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000953 llvm::SmallVector<const Expr *, 8> LHSExprs;
954 llvm::SmallVector<const Expr *, 8> RHSExprs;
955 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000956 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000957 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000958 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000959 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000960 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
961 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
962 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
963 }
964 if (HasAtLeastOneReduction) {
965 // Emit nowait reduction if nowait clause is present or directive is a
966 // parallel directive (it always has implicit barrier).
967 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000968 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000969 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000970 isOpenMPParallelDirective(D.getDirectiveKind()) ||
971 D.getDirectiveKind() == OMPD_simd,
972 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000973 }
974}
975
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000976static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
977 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000978 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000980 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000981 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
982 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000983 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000984 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000985 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000986 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000987 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
988 /*IgnoreResultAssign*/ true);
989 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
990 CGF, NumThreads, NumThreadsClause->getLocStart());
991 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000992 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000993 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000994 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
995 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
996 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000997 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000998 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
999 if (C->getNameModifier() == OMPD_unknown ||
1000 C->getNameModifier() == OMPD_parallel) {
1001 IfCond = C->getCondition();
1002 break;
1003 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001004 }
1005 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001006 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001007}
1008
1009void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001010 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001011 // Emit parallel region as a standalone region.
1012 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1013 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001014 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001015 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1016 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001017 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001018 // propagation master's thread values of threadprivate variables to local
1019 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001020 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1021 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1022 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001023 }
1024 CGF.EmitOMPPrivateClause(S, PrivateScope);
1025 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1026 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001027 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001028 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001029 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001030 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +00001031}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001032
Alexey Bataev0f34da12015-07-02 04:17:07 +00001033void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1034 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001035 RunCleanupsScope BodyScope(*this);
1036 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001037 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001038 EmitIgnoredExpr(I);
1039 }
Alexander Musman3276a272015-03-21 10:12:56 +00001040 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001041 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001042 for (auto U : C->updates()) {
1043 EmitIgnoredExpr(U);
1044 }
1045 }
1046
Alexander Musmana5f070a2014-10-01 06:03:56 +00001047 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001048 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001049 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001050 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001051 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001052 // The end (updates/cleanups).
1053 EmitBlock(Continue.getBlock());
1054 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001055 // TODO: Update lastprivates if the SeparateIter flag is true.
1056 // This will be implemented in a follow-up OMPLastprivateClause patch, but
1057 // result should be still correct without it, as we do not make these
1058 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +00001059}
1060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001061void CodeGenFunction::EmitOMPInnerLoop(
1062 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1063 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001064 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1065 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001066 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001067
1068 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001069 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001070 EmitBlock(CondBlock);
1071 LoopStack.push(CondBlock);
1072
1073 // If there are any cleanups between here and the loop-exit scope,
1074 // create a block to stage a loop exit along.
1075 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001076 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001077 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001078
Alexander Musmand196ef22014-10-07 08:57:09 +00001079 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001080
Alexey Bataev2df54a02015-03-12 08:53:29 +00001081 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001082 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001083 if (ExitBlock != LoopExit.getBlock()) {
1084 EmitBlock(ExitBlock);
1085 EmitBranchThroughCleanup(LoopExit);
1086 }
1087
1088 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001089 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001090
1091 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001092 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001093 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001095 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001096
1097 // Emit "IV = IV + 1" and a back-edge to the condition block.
1098 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001099 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001100 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001101 BreakContinueStack.pop_back();
1102 EmitBranch(CondBlock);
1103 LoopStack.pop();
1104 // Emit the fall-through block.
1105 EmitBlock(LoopExit.getBlock());
1106}
1107
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001108void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001109 if (!HaveInsertPoint())
1110 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001111 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001112 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001113 for (auto Init : C->inits()) {
1114 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001115 auto *OrigVD = cast<VarDecl>(
1116 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1117 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1118 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1119 VD->getInit()->getType(), VK_LValue,
1120 VD->getInit()->getExprLoc());
1121 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1122 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001123 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001124 /*capturedByInit=*/false);
1125 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001126 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001127 // Emit the linear steps for the linear clauses.
1128 // If a step is not constant, it is pre-calculated before the loop.
1129 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1130 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001131 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001132 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001133 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001134 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001135 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001136}
1137
1138static void emitLinearClauseFinal(CodeGenFunction &CGF,
1139 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001140 if (!CGF.HaveInsertPoint())
1141 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001142 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001143 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001144 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001145 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001146 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1147 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001148 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001149 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001150 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001151 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001152 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001153 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001154 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001155 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001156 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001157 }
1158 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001159}
1160
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001161static void emitAlignedClause(CodeGenFunction &CGF,
1162 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001163 if (!CGF.HaveInsertPoint())
1164 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001165 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001166 unsigned ClauseAlignment = 0;
1167 if (auto AlignmentExpr = Clause->getAlignment()) {
1168 auto AlignmentCI =
1169 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1170 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001171 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001172 for (auto E : Clause->varlists()) {
1173 unsigned Alignment = ClauseAlignment;
1174 if (Alignment == 0) {
1175 // OpenMP [2.8.1, Description]
1176 // If no optional parameter is specified, implementation-defined default
1177 // alignments for SIMD instructions on the target platforms are assumed.
1178 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001179 CGF.getContext()
1180 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1181 E->getType()->getPointeeType()))
1182 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001183 }
1184 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1185 "alignment is not power of 2");
1186 if (Alignment != 0) {
1187 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1188 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1189 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001190 }
1191 }
1192}
1193
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001194static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001195 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001196 ArrayRef<Expr *> Counters,
1197 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001198 if (!CGF.HaveInsertPoint())
1199 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001200 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001201 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001202 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1203 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001204 Address Addr = Address::invalid();
1205 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001206 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001207 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001208 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001209 Addr = VarEmission.getAllocatedAddress();
1210 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001211 });
John McCall7f416cc2015-09-08 08:05:57 +00001212 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001213 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001214 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001215}
1216
Alexey Bataev62dbb972015-04-22 11:59:37 +00001217static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1218 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1219 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001220 if (!CGF.HaveInsertPoint())
1221 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001222 {
1223 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001224 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1225 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001226 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001227 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001228 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001229 CGF.EmitIgnoredExpr(I);
1230 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001231 }
1232 // Check that loop is executed at least one time.
1233 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1234}
1235
Alexander Musman3276a272015-03-21 10:12:56 +00001236static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001237emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001238 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001239 if (!CGF.HaveInsertPoint())
1240 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001241 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001242 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001243 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001244 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1245 auto *PrivateVD =
1246 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001247 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001248 // Emit private VarDecl with copy init.
1249 CGF.EmitVarDecl(*PrivateVD);
1250 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001251 });
1252 assert(IsRegistered && "linear var already registered as private");
1253 // Silence the warning about unused variable.
1254 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001255 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001256 }
1257 }
1258}
1259
Alexey Bataev45bfad52015-08-21 12:19:04 +00001260static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001261 const OMPExecutableDirective &D,
1262 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001263 if (!CGF.HaveInsertPoint())
1264 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001265 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001266 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1267 /*ignoreResult=*/true);
1268 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1269 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1270 // In presence of finite 'safelen', it may be unsafe to mark all
1271 // the memory instructions parallel, because loop-carried
1272 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001273 if (!IsMonotonic)
1274 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001275 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001276 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1277 /*ignoreResult=*/true);
1278 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001279 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001280 // In presence of finite 'safelen', it may be unsafe to mark all
1281 // the memory instructions parallel, because loop-carried
1282 // dependences of 'safelen' iterations are possible.
1283 CGF.LoopStack.setParallel(false);
1284 }
1285}
1286
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001287void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1288 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001289 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001290 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001291 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001292 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001293}
1294
1295void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001296 if (!HaveInsertPoint())
1297 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001298 auto IC = D.counters().begin();
1299 for (auto F : D.finals()) {
1300 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001301 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001302 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1303 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1304 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001305 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001306 OMPPrivateScope VarScope(*this);
1307 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001308 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 (void)VarScope.Privatize();
1310 EmitIgnoredExpr(F);
1311 }
1312 ++IC;
1313 }
1314 emitLinearClauseFinal(*this, D);
1315}
1316
Alexander Musman515ad8c2014-05-22 08:54:05 +00001317void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001318 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001319 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001320 // for (IV in 0..LastIteration) BODY;
1321 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001322 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001324
Alexey Bataev62dbb972015-04-22 11:59:37 +00001325 // Emit: if (PreCond) - begin.
1326 // If the condition constant folds and can be elided, avoid emitting the
1327 // whole loop.
1328 bool CondConstant;
1329 llvm::BasicBlock *ContBlock = nullptr;
1330 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1331 if (!CondConstant)
1332 return;
1333 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001334 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1335 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001336 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1337 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001338 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001339 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001340 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001341
1342 // Emit the loop iteration variable.
1343 const Expr *IVExpr = S.getIterationVariable();
1344 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1345 CGF.EmitVarDecl(*IVDecl);
1346 CGF.EmitIgnoredExpr(S.getInit());
1347
1348 // Emit the iterations count variable.
1349 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001350 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1352 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1353 // Emit calculation of the iterations count.
1354 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001355 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001356
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001357 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001358
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001359 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001360 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001361 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001362 {
1363 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001364 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1365 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001366 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001367 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001368 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001369 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001370 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001371 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1372 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001373 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001374 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001375 CGF.EmitStopPoint(&S);
1376 },
1377 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001378 // Emit final copy of the lastprivate variables at the end of loops.
1379 if (HasLastprivateClause) {
1380 CGF.EmitOMPLastprivateClauseFinal(S);
1381 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001382 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001383 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001384 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001385 // Emit: if (PreCond) - end.
1386 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001387 CGF.EmitBranch(ContBlock);
1388 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001389 }
1390 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001391 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001392}
1393
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001394void CodeGenFunction::EmitOMPForOuterLoop(
1395 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1396 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1397 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001398 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001399
1400 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001401 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001402
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001403 assert((Ordered ||
1404 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001405 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001406
1407 // Emit outer loop.
1408 //
1409 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001410 // When schedule(dynamic,chunk_size) is specified, the iterations are
1411 // distributed to threads in the team in chunks as the threads request them.
1412 // Each thread executes a chunk of iterations, then requests another chunk,
1413 // until no chunks remain to be distributed. Each chunk contains chunk_size
1414 // iterations, except for the last chunk to be distributed, which may have
1415 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1416 //
1417 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1418 // to threads in the team in chunks as the executing threads request them.
1419 // Each thread executes a chunk of iterations, then requests another chunk,
1420 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1421 // each chunk is proportional to the number of unassigned iterations divided
1422 // by the number of threads in the team, decreasing to 1. For a chunk_size
1423 // with value k (greater than 1), the size of each chunk is determined in the
1424 // same way, with the restriction that the chunks do not contain fewer than k
1425 // iterations (except for the last chunk to be assigned, which may have fewer
1426 // than k iterations).
1427 //
1428 // When schedule(auto) is specified, the decision regarding scheduling is
1429 // delegated to the compiler and/or runtime system. The programmer gives the
1430 // implementation the freedom to choose any possible mapping of iterations to
1431 // threads in the team.
1432 //
1433 // When schedule(runtime) is specified, the decision regarding scheduling is
1434 // deferred until run time, and the schedule and chunk size are taken from the
1435 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1436 // implementation defined
1437 //
1438 // while(__kmpc_dispatch_next(&LB, &UB)) {
1439 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001440 // while (idx <= UB) { BODY; ++idx;
1441 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1442 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001443 // }
1444 //
1445 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001446 // When schedule(static, chunk_size) is specified, iterations are divided into
1447 // chunks of size chunk_size, and the chunks are assigned to the threads in
1448 // the team in a round-robin fashion in the order of the thread number.
1449 //
1450 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1451 // while (idx <= UB) { BODY; ++idx; } // inner loop
1452 // LB = LB + ST;
1453 // UB = UB + ST;
1454 // }
1455 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001456
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001457 const Expr *IVExpr = S.getIterationVariable();
1458 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1459 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1460
John McCall7f416cc2015-09-08 08:05:57 +00001461 if (DynamicOrOrdered) {
1462 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1463 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1464 IVSize, IVSigned, Ordered, UBVal, Chunk);
1465 } else {
1466 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1467 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1468 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001469
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001470 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1471
1472 // Start the loop with a block that tests the condition.
1473 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1474 EmitBlock(CondBlock);
1475 LoopStack.push(CondBlock);
1476
1477 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001478 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001479 // UB = min(UB, GlobalUB)
1480 EmitIgnoredExpr(S.getEnsureUpperBound());
1481 // IV = LB
1482 EmitIgnoredExpr(S.getInit());
1483 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001484 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001485 } else {
1486 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1487 IL, LB, UB, ST);
1488 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001489
1490 // If there are any cleanups between here and the loop-exit scope,
1491 // create a block to stage a loop exit along.
1492 auto ExitBlock = LoopExit.getBlock();
1493 if (LoopScope.requiresCleanups())
1494 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1495
1496 auto LoopBody = createBasicBlock("omp.dispatch.body");
1497 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1498 if (ExitBlock != LoopExit.getBlock()) {
1499 EmitBlock(ExitBlock);
1500 EmitBranchThroughCleanup(LoopExit);
1501 }
1502 EmitBlock(LoopBody);
1503
Alexander Musman92bdaab2015-03-12 13:37:50 +00001504 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1505 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001506 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001507 EmitIgnoredExpr(S.getInit());
1508
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001509 // Create a block for the increment.
1510 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1511 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1512
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001513 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1514 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001515 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1516 LoopStack.setParallel(!IsMonotonic);
1517 else
1518 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001519
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001520 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001521 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1522 [&S, LoopExit](CodeGenFunction &CGF) {
1523 CGF.EmitOMPLoopBody(S, LoopExit);
1524 CGF.EmitStopPoint(&S);
1525 },
1526 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1527 if (Ordered) {
1528 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1529 CGF, Loc, IVSize, IVSigned);
1530 }
1531 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001532
1533 EmitBlock(Continue.getBlock());
1534 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001535 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001536 // Emit "LB = LB + Stride", "UB = UB + Stride".
1537 EmitIgnoredExpr(S.getNextLowerBound());
1538 EmitIgnoredExpr(S.getNextUpperBound());
1539 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001540
1541 EmitBranch(CondBlock);
1542 LoopStack.pop();
1543 // Emit the fall-through block.
1544 EmitBlock(LoopExit.getBlock());
1545
1546 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001547 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001548 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001549}
1550
Alexander Musmanc6388682014-12-15 07:07:06 +00001551/// \brief Emit a helper variable and return corresponding lvalue.
1552static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1553 const DeclRefExpr *Helper) {
1554 auto VDecl = cast<VarDecl>(Helper->getDecl());
1555 CGF.EmitVarDecl(*VDecl);
1556 return CGF.EmitLValue(Helper);
1557}
1558
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001559namespace {
1560 struct ScheduleKindModifiersTy {
1561 OpenMPScheduleClauseKind Kind;
1562 OpenMPScheduleClauseModifier M1;
1563 OpenMPScheduleClauseModifier M2;
1564 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1565 OpenMPScheduleClauseModifier M1,
1566 OpenMPScheduleClauseModifier M2)
1567 : Kind(Kind), M1(M1), M2(M2) {}
1568 };
1569} // namespace
1570
Alexey Bataev38e89532015-04-16 04:54:05 +00001571bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001572 // Emit the loop iteration variable.
1573 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1574 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1575 EmitVarDecl(*IVDecl);
1576
1577 // Emit the iterations count variable.
1578 // If it is not a variable, Sema decided to calculate iterations count on each
1579 // iteration (e.g., it is foldable into a constant).
1580 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1581 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1582 // Emit calculation of the iterations count.
1583 EmitIgnoredExpr(S.getCalcLastIteration());
1584 }
1585
1586 auto &RT = CGM.getOpenMPRuntime();
1587
Alexey Bataev38e89532015-04-16 04:54:05 +00001588 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001589 // Check pre-condition.
1590 {
1591 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001592 // If the condition constant folds and can be elided, avoid emitting the
1593 // whole loop.
1594 bool CondConstant;
1595 llvm::BasicBlock *ContBlock = nullptr;
1596 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1597 if (!CondConstant)
1598 return false;
1599 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001600 auto *ThenBlock = createBasicBlock("omp.precond.then");
1601 ContBlock = createBasicBlock("omp.precond.end");
1602 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001603 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001604 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001605 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001606 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001607
1608 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001609 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001610 // Emit 'then' code.
1611 {
1612 // Emit helper vars inits.
1613 LValue LB =
1614 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1615 LValue UB =
1616 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1617 LValue ST =
1618 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1619 LValue IL =
1620 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1621
1622 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001623 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1624 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001625 // initialization of firstprivate variables and post-update of
1626 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001627 CGM.getOpenMPRuntime().emitBarrierCall(
1628 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1629 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001630 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001631 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001632 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001633 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001634 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1635 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001636 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001637 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001638
1639 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001640 llvm::Value *Chunk = nullptr;
1641 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1642 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1643 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1644 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1645 ScheduleKind = C->getScheduleKind();
1646 M1 = C->getFirstScheduleModifier();
1647 M2 = C->getSecondScheduleModifier();
1648 if (const auto *Ch = C->getChunkSize()) {
1649 Chunk = EmitScalarExpr(Ch);
1650 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1651 S.getIterationVariable()->getType(),
1652 S.getLocStart());
1653 }
1654 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001655 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1656 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001657 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001658 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1659 // If the static schedule kind is specified or if the ordered clause is
1660 // specified, and if no monotonic modifier is specified, the effect will
1661 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001662 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001663 /* Chunked */ Chunk != nullptr) &&
1664 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001665 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1666 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001667 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1668 // When no chunk_size is specified, the iteration space is divided into
1669 // chunks that are approximately equal in size, and at most one chunk is
1670 // distributed to each thread. Note that the size of the chunks is
1671 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001672 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1673 IVSize, IVSigned, Ordered,
1674 IL.getAddress(), LB.getAddress(),
1675 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001676 auto LoopExit =
1677 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001678 // UB = min(UB, GlobalUB);
1679 EmitIgnoredExpr(S.getEnsureUpperBound());
1680 // IV = LB;
1681 EmitIgnoredExpr(S.getInit());
1682 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001683 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1684 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001685 [&S, LoopExit](CodeGenFunction &CGF) {
1686 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001687 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001688 },
1689 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001690 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001691 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001692 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001693 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001694 const bool IsMonotonic = Ordered ||
1695 ScheduleKind == OMPC_SCHEDULE_static ||
1696 ScheduleKind == OMPC_SCHEDULE_unknown ||
1697 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1698 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001699 // Emit the outer loop, which requests its work chunk [LB..UB] from
1700 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001701 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001702 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1703 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001704 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001705 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001706 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1707 if (HasLastprivateClause)
1708 EmitOMPLastprivateClauseFinal(
1709 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001710 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001711 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1712 EmitOMPSimdFinal(S);
1713 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001714 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001715 if (ContBlock) {
1716 EmitBranch(ContBlock);
1717 EmitBlock(ContBlock, true);
1718 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001719 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001720 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001721}
1722
1723void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001724 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001725 {
1726 OMPLexicalScope Scope(*this, S);
1727 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1728 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1729 };
1730 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1731 S.hasCancel());
1732 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001733
1734 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001735 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001736 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1737 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001738}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001739
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001740void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001741 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001742 {
1743 OMPLexicalScope Scope(*this, S);
1744 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1745 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1746 };
1747 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1748 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001749
1750 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001751 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001752 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1753 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001754}
1755
Alexey Bataev2df54a02015-03-12 08:53:29 +00001756static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1757 const Twine &Name,
1758 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001759 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001760 if (Init)
1761 CGF.EmitScalarInit(Init, LVal);
1762 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001763}
1764
Alexey Bataev3392d762016-02-16 11:18:12 +00001765void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001766 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1767 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001768 bool HasLastprivates = false;
1769 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1770 auto &C = CGF.CGM.getContext();
1771 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1772 // Emit helper vars inits.
1773 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1774 CGF.Builder.getInt32(0));
1775 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1776 : CGF.Builder.getInt32(0);
1777 LValue UB =
1778 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1779 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1780 CGF.Builder.getInt32(1));
1781 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1782 CGF.Builder.getInt32(0));
1783 // Loop counter.
1784 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1785 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1786 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1787 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1788 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1789 // Generate condition for loop.
1790 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1791 OK_Ordinary, S.getLocStart(),
1792 /*fpContractable=*/false);
1793 // Increment for loop counter.
1794 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1795 S.getLocStart());
1796 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1797 // Iterate through all sections and emit a switch construct:
1798 // switch (IV) {
1799 // case 0:
1800 // <SectionStmt[0]>;
1801 // break;
1802 // ...
1803 // case <NumSection> - 1:
1804 // <SectionStmt[<NumSection> - 1]>;
1805 // break;
1806 // }
1807 // .omp.sections.exit:
1808 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1809 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1810 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1811 CS == nullptr ? 1 : CS->size());
1812 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001813 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001814 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001815 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1816 CGF.EmitBlock(CaseBB);
1817 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001818 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001819 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001820 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001821 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001822 } else {
1823 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1824 CGF.EmitBlock(CaseBB);
1825 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1826 CGF.EmitStmt(Stmt);
1827 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001828 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001829 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001830 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001831
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001832 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1833 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001834 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001835 // initialization of firstprivate variables and post-update of lastprivate
1836 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001837 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1838 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1839 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001840 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001841 CGF.EmitOMPPrivateClause(S, LoopScope);
1842 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1843 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1844 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001845
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001846 // Emit static non-chunked loop.
1847 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1848 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1849 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1850 UB.getAddress(), ST.getAddress());
1851 // UB = min(UB, GlobalUB);
1852 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1853 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1854 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1855 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1856 // IV = LB;
1857 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1858 // while (idx <= UB) { BODY; ++idx; }
1859 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1860 [](CodeGenFunction &) {});
1861 // Tell the runtime we are done.
1862 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1863 CGF.EmitOMPReductionClauseFinal(S);
1864
1865 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1866 if (HasLastprivates)
1867 CGF.EmitOMPLastprivateClauseFinal(
1868 S, CGF.Builder.CreateIsNotNull(
1869 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001870 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001871
1872 bool HasCancel = false;
1873 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1874 HasCancel = OSD->hasCancel();
1875 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1876 HasCancel = OPSD->hasCancel();
1877 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1878 HasCancel);
1879 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1880 // clause. Otherwise the barrier will be generated by the codegen for the
1881 // directive.
1882 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001883 // Emit implicit barrier to synchronize threads and avoid data races on
1884 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001885 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1886 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001887 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001888}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001889
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001890void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001891 {
1892 OMPLexicalScope Scope(*this, S);
1893 EmitSections(S);
1894 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001895 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001896 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001897 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1898 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001899 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001900}
1901
1902void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001903 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001904 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1905 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001906 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001907 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1908 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001909}
1910
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001911void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001912 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001913 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001914 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001915 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001916 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001917 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001918 // Build a list of copyprivate variables along with helper expressions
1919 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001920 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001921 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001922 DestExprs.append(C->destination_exprs().begin(),
1923 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001924 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001925 AssignmentOps.append(C->assignment_ops().begin(),
1926 C->assignment_ops().end());
1927 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001928 bool HasFirstprivates;
1929 {
1930 OMPLexicalScope Scope(*this, S);
1931 // Emit code for 'single' region along with 'copyprivate' clauses
1932 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1933 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1934 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
1935 CGF.EmitOMPPrivateClause(S, SingleScope);
1936 (void)SingleScope.Privatize();
Alexey Bataev5521d782015-04-24 04:21:15 +00001937
Alexey Bataev3392d762016-02-16 11:18:12 +00001938 CGF.EmitStmt(
1939 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1940 };
1941 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1942 CopyprivateVars, DestExprs,
1943 SrcExprs, AssignmentOps);
1944 }
1945 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1946 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1947 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
1948 CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001949 CGM.getOpenMPRuntime().emitBarrierCall(
1950 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001951 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001952 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001953}
1954
Alexey Bataev8d690652014-12-04 07:23:53 +00001955void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001956 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001957 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1958 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001959 };
1960 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001961}
1962
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001963void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001964 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001965 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1966 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001967 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001968 Expr *Hint = nullptr;
1969 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1970 Hint = HintClause->getHint();
1971 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1972 S.getDirectiveName().getAsString(),
1973 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001974}
1975
Alexey Bataev671605e2015-04-13 05:28:11 +00001976void CodeGenFunction::EmitOMPParallelForDirective(
1977 const OMPParallelForDirective &S) {
1978 // Emit directive as a combined directive that consists of two implicit
1979 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001980 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001981 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1982 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001983 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001984 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001985}
1986
Alexander Musmane4e893b2014-09-23 09:33:00 +00001987void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001988 const OMPParallelForSimdDirective &S) {
1989 // Emit directive as a combined directive that consists of two implicit
1990 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001991 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001992 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1993 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001994 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001995 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001996}
1997
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001998void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001999 const OMPParallelSectionsDirective &S) {
2000 // Emit directive as a combined directive that consists of two implicit
2001 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002002 OMPLexicalScope Scope(*this, S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002003 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002004 CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002005 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002006 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002007}
2008
Alexey Bataev62b63b12015-03-10 07:28:44 +00002009void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2010 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002011 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002012 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2013 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2014 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002015 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002016 // The first function argument for tasks is a thread id, the second one is a
2017 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002018 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2019 // Get list of private variables.
2020 llvm::SmallVector<const Expr *, 8> PrivateVars;
2021 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002022 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002023 auto IRef = C->varlist_begin();
2024 for (auto *IInit : C->private_copies()) {
2025 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2026 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2027 PrivateVars.push_back(*IRef);
2028 PrivateCopies.push_back(IInit);
2029 }
2030 ++IRef;
2031 }
2032 }
2033 EmittedAsPrivate.clear();
2034 // Get list of firstprivate variables.
2035 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2036 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2037 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002038 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002039 auto IRef = C->varlist_begin();
2040 auto IElemInitRef = C->inits().begin();
2041 for (auto *IInit : C->private_copies()) {
2042 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2043 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2044 FirstprivateVars.push_back(*IRef);
2045 FirstprivateCopies.push_back(IInit);
2046 FirstprivateInits.push_back(*IElemInitRef);
2047 }
2048 ++IRef, ++IElemInitRef;
2049 }
2050 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002051 // Build list of dependences.
2052 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2053 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002054 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002055 for (auto *IRef : C->varlists()) {
2056 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2057 }
2058 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002059 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2060 CodeGenFunction &CGF) {
2061 // Set proper addresses for generated private copies.
2062 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2063 OMPPrivateScope Scope(CGF);
2064 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002065 auto *CopyFn = CGF.Builder.CreateLoad(
2066 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2067 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2068 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002069 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002070 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002071 PrivatePtrs;
2072 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2073 CallArgs.push_back(PrivatesPtr);
2074 for (auto *E : PrivateVars) {
2075 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002076 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002077 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2078 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002079 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002080 }
2081 for (auto *E : FirstprivateVars) {
2082 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002083 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002084 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2085 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002086 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002087 }
2088 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2089 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002090 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2091 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002092 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2093 }
2094 }
2095 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002096 if (*PartId) {
2097 // TODO: emit code for untied tasks.
2098 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002099 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002100 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002101 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2102 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002103 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002104 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002105 // Check if the task is final
2106 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002107 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002108 // If the condition constant folds and can be elided, try to avoid emitting
2109 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002110 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002111 bool CondConstant;
2112 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2113 Final.setInt(CondConstant);
2114 else
2115 Final.setPointer(EvaluateExprAsBool(Cond));
2116 } else {
2117 // By default the task is not final.
2118 Final.setInt(/*IntVal=*/false);
2119 }
2120 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002121 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002122 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2123 if (C->getNameModifier() == OMPD_unknown ||
2124 C->getNameModifier() == OMPD_task) {
2125 IfCond = C->getCondition();
2126 break;
2127 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002128 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002129 CGM.getOpenMPRuntime().emitTaskCall(
2130 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002131 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002132 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002133}
2134
Alexey Bataev9f797f32015-02-05 05:57:51 +00002135void CodeGenFunction::EmitOMPTaskyieldDirective(
2136 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002137 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002138}
2139
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002140void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002141 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002142}
2143
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002144void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2145 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002146}
2147
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002148void CodeGenFunction::EmitOMPTaskgroupDirective(
2149 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002150 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002151 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2152 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002153 };
2154 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2155}
2156
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002157void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002158 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002159 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002160 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2161 FlushClause->varlist_end());
2162 }
2163 return llvm::None;
2164 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002165}
2166
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002167void CodeGenFunction::EmitOMPDistributeDirective(
2168 const OMPDistributeDirective &S) {
2169 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2170}
2171
Alexey Bataev5f600d62015-09-29 03:48:57 +00002172static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2173 const CapturedStmt *S) {
2174 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2175 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2176 CGF.CapturedStmtInfo = &CapStmtInfo;
2177 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2178 Fn->addFnAttr(llvm::Attribute::NoInline);
2179 return Fn;
2180}
2181
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002182void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002183 if (!S.getAssociatedStmt())
2184 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002185 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002186 auto *C = S.getSingleClause<OMPSIMDClause>();
2187 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2188 if (C) {
2189 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2190 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2191 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2192 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2193 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2194 } else {
2195 CGF.EmitStmt(
2196 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2197 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002198 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002199 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002200}
2201
Alexey Bataevb57056f2015-01-22 06:17:56 +00002202static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002203 QualType SrcType, QualType DestType,
2204 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002205 assert(CGF.hasScalarEvaluationKind(DestType) &&
2206 "DestType must have scalar evaluation kind.");
2207 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2208 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002209 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2210 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002211 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002212 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002213}
2214
2215static CodeGenFunction::ComplexPairTy
2216convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002217 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002218 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2219 "DestType must have complex evaluation kind.");
2220 CodeGenFunction::ComplexPairTy ComplexVal;
2221 if (Val.isScalar()) {
2222 // Convert the input element to the element type of the complex.
2223 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002224 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2225 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002226 ComplexVal = CodeGenFunction::ComplexPairTy(
2227 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2228 } else {
2229 assert(Val.isComplex() && "Must be a scalar or complex.");
2230 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2231 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2232 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002233 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002234 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002235 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002236 }
2237 return ComplexVal;
2238}
2239
Alexey Bataev5e018f92015-04-23 06:35:10 +00002240static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2241 LValue LVal, RValue RVal) {
2242 if (LVal.isGlobalReg()) {
2243 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2244 } else {
2245 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2246 : llvm::Monotonic,
2247 LVal.isVolatile(), /*IsInit=*/false);
2248 }
2249}
2250
Alexey Bataev8524d152016-01-21 12:35:58 +00002251void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2252 QualType RValTy, SourceLocation Loc) {
2253 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002254 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002255 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2256 *this, RVal, RValTy, LVal.getType(), Loc)),
2257 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002258 break;
2259 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002260 EmitStoreOfComplex(
2261 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002262 /*isInit=*/false);
2263 break;
2264 case TEK_Aggregate:
2265 llvm_unreachable("Must be a scalar or complex.");
2266 }
2267}
2268
Alexey Bataevb57056f2015-01-22 06:17:56 +00002269static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2270 const Expr *X, const Expr *V,
2271 SourceLocation Loc) {
2272 // v = x;
2273 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2274 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2275 LValue XLValue = CGF.EmitLValue(X);
2276 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002277 RValue Res = XLValue.isGlobalReg()
2278 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2279 : CGF.EmitAtomicLoad(XLValue, Loc,
2280 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002281 : llvm::Monotonic,
2282 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002283 // OpenMP, 2.12.6, atomic Construct
2284 // Any atomic construct with a seq_cst clause forces the atomically
2285 // performed operation to include an implicit flush operation without a
2286 // list.
2287 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002288 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002289 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002290}
2291
Alexey Bataevb8329262015-02-27 06:33:30 +00002292static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2293 const Expr *X, const Expr *E,
2294 SourceLocation Loc) {
2295 // x = expr;
2296 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002297 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002298 // OpenMP, 2.12.6, atomic Construct
2299 // Any atomic construct with a seq_cst clause forces the atomically
2300 // performed operation to include an implicit flush operation without a
2301 // list.
2302 if (IsSeqCst)
2303 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2304}
2305
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002306static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2307 RValue Update,
2308 BinaryOperatorKind BO,
2309 llvm::AtomicOrdering AO,
2310 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002311 auto &Context = CGF.CGM.getContext();
2312 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002313 // expression is simple and atomic is allowed for the given type for the
2314 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002315 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002316 !Update.getScalarVal()->getType()->isIntegerTy() ||
2317 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2318 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002319 X.getAddress().getElementType())) ||
2320 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002321 !Context.getTargetInfo().hasBuiltinAtomic(
2322 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002323 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002324
2325 llvm::AtomicRMWInst::BinOp RMWOp;
2326 switch (BO) {
2327 case BO_Add:
2328 RMWOp = llvm::AtomicRMWInst::Add;
2329 break;
2330 case BO_Sub:
2331 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002332 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002333 RMWOp = llvm::AtomicRMWInst::Sub;
2334 break;
2335 case BO_And:
2336 RMWOp = llvm::AtomicRMWInst::And;
2337 break;
2338 case BO_Or:
2339 RMWOp = llvm::AtomicRMWInst::Or;
2340 break;
2341 case BO_Xor:
2342 RMWOp = llvm::AtomicRMWInst::Xor;
2343 break;
2344 case BO_LT:
2345 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2346 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2347 : llvm::AtomicRMWInst::Max)
2348 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2349 : llvm::AtomicRMWInst::UMax);
2350 break;
2351 case BO_GT:
2352 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2353 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2354 : llvm::AtomicRMWInst::Min)
2355 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2356 : llvm::AtomicRMWInst::UMin);
2357 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002358 case BO_Assign:
2359 RMWOp = llvm::AtomicRMWInst::Xchg;
2360 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002361 case BO_Mul:
2362 case BO_Div:
2363 case BO_Rem:
2364 case BO_Shl:
2365 case BO_Shr:
2366 case BO_LAnd:
2367 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002368 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002369 case BO_PtrMemD:
2370 case BO_PtrMemI:
2371 case BO_LE:
2372 case BO_GE:
2373 case BO_EQ:
2374 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002375 case BO_AddAssign:
2376 case BO_SubAssign:
2377 case BO_AndAssign:
2378 case BO_OrAssign:
2379 case BO_XorAssign:
2380 case BO_MulAssign:
2381 case BO_DivAssign:
2382 case BO_RemAssign:
2383 case BO_ShlAssign:
2384 case BO_ShrAssign:
2385 case BO_Comma:
2386 llvm_unreachable("Unsupported atomic update operation");
2387 }
2388 auto *UpdateVal = Update.getScalarVal();
2389 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2390 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002391 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002392 X.getType()->hasSignedIntegerRepresentation());
2393 }
John McCall7f416cc2015-09-08 08:05:57 +00002394 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002395 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002396}
2397
Alexey Bataev5e018f92015-04-23 06:35:10 +00002398std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002399 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2400 llvm::AtomicOrdering AO, SourceLocation Loc,
2401 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2402 // Update expressions are allowed to have the following forms:
2403 // x binop= expr; -> xrval + expr;
2404 // x++, ++x -> xrval + 1;
2405 // x--, --x -> xrval - 1;
2406 // x = x binop expr; -> xrval binop expr
2407 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002408 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2409 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002410 if (X.isGlobalReg()) {
2411 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2412 // 'xrval'.
2413 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2414 } else {
2415 // Perform compare-and-swap procedure.
2416 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002417 }
2418 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002419 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002420}
2421
2422static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2423 const Expr *X, const Expr *E,
2424 const Expr *UE, bool IsXLHSInRHSPart,
2425 SourceLocation Loc) {
2426 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2427 "Update expr in 'atomic update' must be a binary operator.");
2428 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2429 // Update expressions are allowed to have the following forms:
2430 // x binop= expr; -> xrval + expr;
2431 // x++, ++x -> xrval + 1;
2432 // x--, --x -> xrval - 1;
2433 // x = x binop expr; -> xrval binop expr
2434 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002435 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002436 LValue XLValue = CGF.EmitLValue(X);
2437 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002438 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002439 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2440 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2441 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2442 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2443 auto Gen =
2444 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2445 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2446 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2447 return CGF.EmitAnyExpr(UE);
2448 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002449 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2450 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2451 // OpenMP, 2.12.6, atomic Construct
2452 // Any atomic construct with a seq_cst clause forces the atomically
2453 // performed operation to include an implicit flush operation without a
2454 // list.
2455 if (IsSeqCst)
2456 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2457}
2458
2459static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002460 QualType SourceType, QualType ResType,
2461 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002462 switch (CGF.getEvaluationKind(ResType)) {
2463 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002464 return RValue::get(
2465 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002466 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002467 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002468 return RValue::getComplex(Res.first, Res.second);
2469 }
2470 case TEK_Aggregate:
2471 break;
2472 }
2473 llvm_unreachable("Must be a scalar or complex.");
2474}
2475
2476static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2477 bool IsPostfixUpdate, const Expr *V,
2478 const Expr *X, const Expr *E,
2479 const Expr *UE, bool IsXLHSInRHSPart,
2480 SourceLocation Loc) {
2481 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2482 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2483 RValue NewVVal;
2484 LValue VLValue = CGF.EmitLValue(V);
2485 LValue XLValue = CGF.EmitLValue(X);
2486 RValue ExprRValue = CGF.EmitAnyExpr(E);
2487 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2488 QualType NewVValType;
2489 if (UE) {
2490 // 'x' is updated with some additional value.
2491 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2492 "Update expr in 'atomic capture' must be a binary operator.");
2493 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2494 // Update expressions are allowed to have the following forms:
2495 // x binop= expr; -> xrval + expr;
2496 // x++, ++x -> xrval + 1;
2497 // x--, --x -> xrval - 1;
2498 // x = x binop expr; -> xrval binop expr
2499 // x = expr Op x; - > expr binop xrval;
2500 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2501 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2502 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2503 NewVValType = XRValExpr->getType();
2504 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2505 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2506 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2507 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2508 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2509 RValue Res = CGF.EmitAnyExpr(UE);
2510 NewVVal = IsPostfixUpdate ? XRValue : Res;
2511 return Res;
2512 };
2513 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2514 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2515 if (Res.first) {
2516 // 'atomicrmw' instruction was generated.
2517 if (IsPostfixUpdate) {
2518 // Use old value from 'atomicrmw'.
2519 NewVVal = Res.second;
2520 } else {
2521 // 'atomicrmw' does not provide new value, so evaluate it using old
2522 // value of 'x'.
2523 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2524 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2525 NewVVal = CGF.EmitAnyExpr(UE);
2526 }
2527 }
2528 } else {
2529 // 'x' is simply rewritten with some 'expr'.
2530 NewVValType = X->getType().getNonReferenceType();
2531 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002532 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002533 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2534 NewVVal = XRValue;
2535 return ExprRValue;
2536 };
2537 // Try to perform atomicrmw xchg, otherwise simple exchange.
2538 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2539 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2540 Loc, Gen);
2541 if (Res.first) {
2542 // 'atomicrmw' instruction was generated.
2543 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2544 }
2545 }
2546 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002547 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002548 // OpenMP, 2.12.6, atomic Construct
2549 // Any atomic construct with a seq_cst clause forces the atomically
2550 // performed operation to include an implicit flush operation without a
2551 // list.
2552 if (IsSeqCst)
2553 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2554}
2555
Alexey Bataevb57056f2015-01-22 06:17:56 +00002556static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002557 bool IsSeqCst, bool IsPostfixUpdate,
2558 const Expr *X, const Expr *V, const Expr *E,
2559 const Expr *UE, bool IsXLHSInRHSPart,
2560 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002561 switch (Kind) {
2562 case OMPC_read:
2563 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2564 break;
2565 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002566 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2567 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002568 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002569 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002570 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2571 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002572 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002573 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2574 IsXLHSInRHSPart, Loc);
2575 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002576 case OMPC_if:
2577 case OMPC_final:
2578 case OMPC_num_threads:
2579 case OMPC_private:
2580 case OMPC_firstprivate:
2581 case OMPC_lastprivate:
2582 case OMPC_reduction:
2583 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002584 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002585 case OMPC_collapse:
2586 case OMPC_default:
2587 case OMPC_seq_cst:
2588 case OMPC_shared:
2589 case OMPC_linear:
2590 case OMPC_aligned:
2591 case OMPC_copyin:
2592 case OMPC_copyprivate:
2593 case OMPC_flush:
2594 case OMPC_proc_bind:
2595 case OMPC_schedule:
2596 case OMPC_ordered:
2597 case OMPC_nowait:
2598 case OMPC_untied:
2599 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002600 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002601 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002602 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002603 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002604 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002605 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002606 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002607 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002608 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002609 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002610 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002611 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002612 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002613 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002614 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002615 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2616 }
2617}
2618
2619void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002620 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002621 OpenMPClauseKind Kind = OMPC_unknown;
2622 for (auto *C : S.clauses()) {
2623 // Find first clause (skip seq_cst clause, if it is first).
2624 if (C->getClauseKind() != OMPC_seq_cst) {
2625 Kind = C->getClauseKind();
2626 break;
2627 }
2628 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002629
2630 const auto *CS =
2631 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002632 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002633 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002634 }
2635 // Processing for statements under 'atomic capture'.
2636 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2637 for (const auto *C : Compound->body()) {
2638 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2639 enterFullExpression(EWC);
2640 }
2641 }
2642 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002643
Alexey Bataev3392d762016-02-16 11:18:12 +00002644 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002645 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2646 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002647 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2648 S.getV(), S.getExpr(), S.getUpdateExpr(),
2649 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002650 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002651 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002652}
2653
Samuel Antaobed3c462015-10-02 16:14:20 +00002654void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002655 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002656 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2657
2658 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002659 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002660
Samuel Antaoee8fb302016-01-06 13:42:12 +00002661 llvm::Function *Fn = nullptr;
2662 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002663
2664 // Check if we have any if clause associated with the directive.
2665 const Expr *IfCond = nullptr;
2666
2667 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2668 IfCond = C->getCondition();
2669 }
2670
2671 // Check if we have any device clause associated with the directive.
2672 const Expr *Device = nullptr;
2673 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2674 Device = C->getDevice();
2675 }
2676
Samuel Antaoee8fb302016-01-06 13:42:12 +00002677 // Check if we have an if clause whose conditional always evaluates to false
2678 // or if we do not have any targets specified. If so the target region is not
2679 // an offload entry point.
2680 bool IsOffloadEntry = true;
2681 if (IfCond) {
2682 bool Val;
2683 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2684 IsOffloadEntry = false;
2685 }
2686 if (CGM.getLangOpts().OMPTargetTriples.empty())
2687 IsOffloadEntry = false;
2688
2689 assert(CurFuncDecl && "No parent declaration for target region!");
2690 StringRef ParentName;
2691 // In case we have Ctors/Dtors we use the complete type variant to produce
2692 // the mangling of the device outlined kernel.
2693 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2694 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2695 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2696 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2697 else
2698 ParentName =
2699 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2700
2701 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2702 IsOffloadEntry);
2703
2704 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002705 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002706}
2707
Alexey Bataev13314bf2014-10-09 04:18:56 +00002708void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2709 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2710}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002711
2712void CodeGenFunction::EmitOMPCancellationPointDirective(
2713 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002714 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2715 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002716}
2717
Alexey Bataev80909872015-07-02 11:25:17 +00002718void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002719 const Expr *IfCond = nullptr;
2720 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2721 if (C->getNameModifier() == OMPD_unknown ||
2722 C->getNameModifier() == OMPD_cancel) {
2723 IfCond = C->getCondition();
2724 break;
2725 }
2726 }
2727 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002728 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002729}
2730
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002731CodeGenFunction::JumpDest
2732CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2733 if (Kind == OMPD_parallel || Kind == OMPD_task)
2734 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002735 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002736 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002737 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002738}
Michael Wong65f367f2015-07-21 13:44:28 +00002739
2740// Generate the instructions for '#pragma omp target data' directive.
2741void CodeGenFunction::EmitOMPTargetDataDirective(
2742 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002743 // emit the code inside the construct for now
2744 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002745 CGM.getOpenMPRuntime().emitInlinedDirective(
2746 *this, OMPD_target_data,
2747 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002748}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002749
Samuel Antaodf67fc42016-01-19 19:15:56 +00002750void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2751 const OMPTargetEnterDataDirective &S) {
2752 // TODO: codegen for target enter data.
2753}
2754
Samuel Antao72590762016-01-19 20:04:50 +00002755void CodeGenFunction::EmitOMPTargetExitDataDirective(
2756 const OMPTargetExitDataDirective &S) {
2757 // TODO: codegen for target exit data.
2758}
2759
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002760void CodeGenFunction::EmitOMPTargetParallelDirective(
2761 const OMPTargetParallelDirective &S) {
2762 // TODO: codegen for target parallel.
2763}
2764
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002765void CodeGenFunction::EmitOMPTargetParallelForDirective(
2766 const OMPTargetParallelForDirective &S) {
2767 // TODO: codegen for target parallel for.
2768}
2769
Alexey Bataev49f6e782015-12-01 04:18:41 +00002770void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2771 // emit the code inside the construct for now
2772 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2773 CGM.getOpenMPRuntime().emitInlinedDirective(
2774 *this, OMPD_taskloop,
2775 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2776}
2777
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002778void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2779 const OMPTaskLoopSimdDirective &S) {
2780 // emit the code inside the construct for now
2781 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2782 CGM.getOpenMPRuntime().emitInlinedDirective(
2783 *this, OMPD_taskloop_simd,
2784 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2785}
2786