blob: 8434cdf2da2cc572c7d00b2e04f3fe9b360f5f76 [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"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
28class OMPLexicalScope {
29 CodeGenFunction::LexicalScope Scope;
30 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +000048 class PostUpdateCleanup final : public EHScopeStack::Cleanup {
49 const OMPExecutableDirective &S;
50
51 public:
52 PostUpdateCleanup(const OMPExecutableDirective &S) : S(S) {}
53
54 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
55 if (!CGF.HaveInsertPoint())
56 return;
57 (void)S;
58 // TODO: add cleanups for clauses that require post update.
59 }
60 };
61
Alexey Bataev3392d762016-02-16 11:18:12 +000062public:
63 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
64 : Scope(CGF, S.getSourceRange()) {
65 emitPreInitStmt(CGF, S);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +000066 CGF.EHStack.pushCleanup<PostUpdateCleanup>(NormalAndEHCleanup, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000067 }
68};
69} // namespace
70
Alexey Bataev1189bd02016-01-26 12:20:39 +000071llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
72 auto &C = getContext();
73 llvm::Value *Size = nullptr;
74 auto SizeInChars = C.getTypeSizeInChars(Ty);
75 if (SizeInChars.isZero()) {
76 // getTypeSizeInChars() returns 0 for a VLA.
77 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
78 llvm::Value *ArraySize;
79 std::tie(ArraySize, Ty) = getVLASize(VAT);
80 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
81 }
82 SizeInChars = C.getTypeSizeInChars(Ty);
83 if (SizeInChars.isZero())
84 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
85 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
86 } else
87 Size = CGM.getSize(SizeInChars);
88 return Size;
89}
90
Alexey Bataev2377fe92015-09-10 08:12:02 +000091void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000092 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000093 const RecordDecl *RD = S.getCapturedRecordDecl();
94 auto CurField = RD->field_begin();
95 auto CurCap = S.captures().begin();
96 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
97 E = S.capture_init_end();
98 I != E; ++I, ++CurField, ++CurCap) {
99 if (CurField->hasCapturedVLAType()) {
100 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000101 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000102 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000103 } else if (CurCap->capturesThis())
104 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000105 else if (CurCap->capturesVariableByCopy())
106 CapturedVars.push_back(
107 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
108 else {
109 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000110 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000111 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000112 }
113}
114
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000115static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
116 StringRef Name, LValue AddrLV,
117 bool isReferenceType = false) {
118 ASTContext &Ctx = CGF.getContext();
119
120 auto *CastedPtr = CGF.EmitScalarConversion(
121 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
122 Ctx.getPointerType(DstType), SourceLocation());
123 auto TmpAddr =
124 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
125 .getAddress();
126
127 // If we are dealing with references we need to return the address of the
128 // reference instead of the reference of the value.
129 if (isReferenceType) {
130 QualType RefType = Ctx.getLValueReferenceType(DstType);
131 auto *RefVal = TmpAddr.getPointer();
132 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
133 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
134 CGF.EmitScalarInit(RefVal, TmpLVal);
135 }
136
137 return TmpAddr;
138}
139
Alexey Bataev2377fe92015-09-10 08:12:02 +0000140llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000141CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000142 assert(
143 CapturedStmtInfo &&
144 "CapturedStmtInfo should be set when generating the captured function");
145 const CapturedDecl *CD = S.getCapturedDecl();
146 const RecordDecl *RD = S.getCapturedRecordDecl();
147 assert(CD->hasBody() && "missing CapturedDecl body");
148
149 // Build the argument list.
150 ASTContext &Ctx = CGM.getContext();
151 FunctionArgList Args;
152 Args.append(CD->param_begin(),
153 std::next(CD->param_begin(), CD->getContextParamPosition()));
154 auto I = S.captures().begin();
155 for (auto *FD : RD->fields()) {
156 QualType ArgType = FD->getType();
157 IdentifierInfo *II = nullptr;
158 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000159
160 // If this is a capture by copy and the type is not a pointer, the outlined
161 // function argument type should be uintptr and the value properly casted to
162 // uintptr. This is necessary given that the runtime library is only able to
163 // deal with pointers. We can pass in the same way the VLA type sizes to the
164 // outlined function.
165 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
166 I->capturesVariableArrayType())
167 ArgType = Ctx.getUIntPtrType();
168
169 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000170 CapVar = I->getCapturedVar();
171 II = CapVar->getIdentifier();
172 } else if (I->capturesThis())
173 II = &getContext().Idents.get("this");
174 else {
175 assert(I->capturesVariableArrayType());
176 II = &getContext().Idents.get("vla");
177 }
178 if (ArgType->isVariablyModifiedType())
179 ArgType = getContext().getVariableArrayDecayedType(ArgType);
180 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
181 FD->getLocation(), II, ArgType));
182 ++I;
183 }
184 Args.append(
185 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
186 CD->param_end());
187
188 // Create the function declaration.
189 FunctionType::ExtInfo ExtInfo;
190 const CGFunctionInfo &FuncInfo =
191 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
192 /*IsVariadic=*/false);
193 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
194
195 llvm::Function *F = llvm::Function::Create(
196 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
197 CapturedStmtInfo->getHelperName(), &CGM.getModule());
198 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
199 if (CD->isNothrow())
200 F->addFnAttr(llvm::Attribute::NoUnwind);
201
202 // Generate the function.
203 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
204 CD->getBody()->getLocStart());
205 unsigned Cnt = CD->getContextParamPosition();
206 I = S.captures().begin();
207 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000208 // If we are capturing a pointer by copy we don't need to do anything, just
209 // use the value that we get from the arguments.
210 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
211 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000212 ++Cnt;
213 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000214 continue;
215 }
216
Alexey Bataev2377fe92015-09-10 08:12:02 +0000217 LValue ArgLVal =
218 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
219 AlignmentSource::Decl);
220 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000221 LValue CastedArgLVal =
222 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
223 Args[Cnt]->getName(), ArgLVal),
224 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000225 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000226 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000227 auto VAT = FD->getCapturedVLAType();
228 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
229 } else if (I->capturesVariable()) {
230 auto *Var = I->getCapturedVar();
231 QualType VarTy = Var->getType();
232 Address ArgAddr = ArgLVal.getAddress();
233 if (!VarTy->isReferenceType()) {
234 ArgAddr = EmitLoadOfReference(
235 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
236 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000237 setAddrOfLocalVar(
238 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000239 } else if (I->capturesVariableByCopy()) {
240 assert(!FD->getType()->isAnyPointerType() &&
241 "Not expecting a captured pointer.");
242 auto *Var = I->getCapturedVar();
243 QualType VarTy = Var->getType();
244 setAddrOfLocalVar(I->getCapturedVar(),
245 castValueFromUintptr(*this, FD->getType(),
246 Args[Cnt]->getName(), ArgLVal,
247 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000248 } else {
249 // If 'this' is captured, load it into CXXThisValue.
250 assert(I->capturesThis());
251 CXXThisValue =
252 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
253 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000254 ++Cnt;
255 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000256 }
257
Serge Pavlov3a561452015-12-06 14:32:39 +0000258 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000259 CapturedStmtInfo->EmitBody(*this, CD->getBody());
260 FinishFunction(CD->getBodyRBrace());
261
262 return F;
263}
264
Alexey Bataev9959db52014-05-06 10:08:46 +0000265//===----------------------------------------------------------------------===//
266// OpenMP Directive Emission
267//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000268void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000269 Address DestAddr, Address SrcAddr, QualType OriginalType,
270 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000271 // Perform element-by-element initialization.
272 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000273
274 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000276 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
277 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
278
279 auto SrcBegin = SrcAddr.getPointer();
280 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000281 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000282 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
283 // The basic structure here is a while-do loop.
284 auto BodyBB = createBasicBlock("omp.arraycpy.body");
285 auto DoneBB = createBasicBlock("omp.arraycpy.done");
286 auto IsEmpty =
287 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
288 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000289
Alexey Bataev420d45b2015-04-14 05:11:24 +0000290 // Enter the loop body, making that address the current address.
291 auto EntryBB = Builder.GetInsertBlock();
292 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000293
294 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
295
296 llvm::PHINode *SrcElementPHI =
297 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
298 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
299 Address SrcElementCurrent =
300 Address(SrcElementPHI,
301 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
302
303 llvm::PHINode *DestElementPHI =
304 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
305 DestElementPHI->addIncoming(DestBegin, EntryBB);
306 Address DestElementCurrent =
307 Address(DestElementPHI,
308 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000309
Alexey Bataev420d45b2015-04-14 05:11:24 +0000310 // Emit copy.
311 CopyGen(DestElementCurrent, SrcElementCurrent);
312
313 // Shift the address forward by one element.
314 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000315 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000316 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000317 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000318 // Check whether we've reached the end.
319 auto Done =
320 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
321 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000322 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
323 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000324
325 // Done.
326 EmitBlock(DoneBB, /*IsFinished=*/true);
327}
328
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000329/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000330/// \param DestAddr Address of the array.
331/// \param Type Type of array.
332/// \param Init Initial expression of array.
333static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
334 QualType Type, const Expr *Init) {
335 // Perform element-by-element initialization.
336 QualType ElementTy;
337
338 // Drill down to the base element type on both arrays.
339 auto ArrayTy = Type->getAsArrayTypeUnsafe();
340 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
341 DestAddr =
342 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
343
344 auto DestBegin = DestAddr.getPointer();
345 // Cast from pointer to array type to pointer to single element.
346 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
347 // The basic structure here is a while-do loop.
348 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
349 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
350 auto IsEmpty =
351 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
352 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
353
354 // Enter the loop body, making that address the current address.
355 auto EntryBB = CGF.Builder.GetInsertBlock();
356 CGF.EmitBlock(BodyBB);
357
358 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
359
360 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
361 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
362 DestElementPHI->addIncoming(DestBegin, EntryBB);
363 Address DestElementCurrent =
364 Address(DestElementPHI,
365 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
366
367 // Emit copy.
368 {
369 CodeGenFunction::RunCleanupsScope InitScope(CGF);
370 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
371 /*IsInitializer=*/false);
372 }
373
374 // Shift the address forward by one element.
375 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
376 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
377 // Check whether we've reached the end.
378 auto Done =
379 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
380 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
381 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
382
383 // Done.
384 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
385}
386
John McCall7f416cc2015-09-08 08:05:57 +0000387void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
388 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000389 const VarDecl *SrcVD, const Expr *Copy) {
390 if (OriginalType->isArrayType()) {
391 auto *BO = dyn_cast<BinaryOperator>(Copy);
392 if (BO && BO->getOpcode() == BO_Assign) {
393 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000394 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000395 } else {
396 // For arrays with complex element types perform element by element
397 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000398 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000400 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000401 // Working with the single array element, so have to remap
402 // destination and source variables to corresponding array
403 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000404 CodeGenFunction::OMPPrivateScope Remap(*this);
405 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000406 return DestElement;
407 });
408 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000409 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000410 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000411 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000412 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000413 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000414 } else {
415 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000416 CodeGenFunction::OMPPrivateScope Remap(*this);
417 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
418 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000419 (void)Remap.Privatize();
420 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000421 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000422 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423}
424
Alexey Bataev69c62a92015-04-15 04:52:20 +0000425bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
426 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000427 if (!HaveInsertPoint())
428 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000429 bool FirstprivateIsLastprivate = false;
430 llvm::DenseSet<const VarDecl *> Lastprivates;
431 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
432 for (const auto *D : C->varlists())
433 Lastprivates.insert(
434 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
435 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000436 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000437 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000438 auto IRef = C->varlist_begin();
439 auto InitsRef = C->inits().begin();
440 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000441 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000442 FirstprivateIsLastprivate =
443 FirstprivateIsLastprivate ||
444 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
445 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
447 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
448 bool IsRegistered;
449 DeclRefExpr DRE(
450 const_cast<VarDecl *>(OrigVD),
451 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
452 OrigVD) != nullptr,
453 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000454 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000455 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000456 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 // Emit VarDecl with copy init for arrays.
458 // Get the address of the original variable captured in current
459 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000460 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000461 auto Emission = EmitAutoVarAlloca(*VD);
462 auto *Init = VD->getInit();
463 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
464 // Perform simple memcpy.
465 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000466 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000467 } else {
468 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000469 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000470 [this, VDInit, Init](Address DestElement,
471 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000472 // Clean up any temporaries needed by the initialization.
473 RunCleanupsScope InitScope(*this);
474 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000475 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000476 EmitAnyExprToMem(Init, DestElement,
477 Init->getType().getQualifiers(),
478 /*IsInitializer*/ false);
479 LocalDeclMap.erase(VDInit);
480 });
481 }
482 EmitAutoVarCleanups(Emission);
483 return Emission.getAllocatedAddress();
484 });
485 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000486 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000487 // Emit private VarDecl with copy init.
488 // Remap temp VDInit variable to the address of the original
489 // variable
490 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000491 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000492 EmitDecl(*VD);
493 LocalDeclMap.erase(VDInit);
494 return GetAddrOfLocalVar(VD);
495 });
496 }
497 assert(IsRegistered &&
498 "firstprivate var already registered as private");
499 // Silence the warning about unused variable.
500 (void)IsRegistered;
501 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000502 ++IRef;
503 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000504 }
505 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000506 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000507}
508
Alexey Bataev03b340a2014-10-21 03:16:40 +0000509void CodeGenFunction::EmitOMPPrivateClause(
510 const OMPExecutableDirective &D,
511 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000512 if (!HaveInsertPoint())
513 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000514 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000515 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000516 auto IRef = C->varlist_begin();
517 for (auto IInit : C->private_copies()) {
518 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000519 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
520 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
521 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000522 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000523 // Emit private VarDecl with copy init.
524 EmitDecl(*VD);
525 return GetAddrOfLocalVar(VD);
526 });
527 assert(IsRegistered && "private var already registered as private");
528 // Silence the warning about unused variable.
529 (void)IsRegistered;
530 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000531 ++IRef;
532 }
533 }
534}
535
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000536bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000537 if (!HaveInsertPoint())
538 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000539 // threadprivate_var1 = master_threadprivate_var1;
540 // operator=(threadprivate_var2, master_threadprivate_var2);
541 // ...
542 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000543 llvm::DenseSet<const VarDecl *> CopiedVars;
544 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000545 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000546 auto IRef = C->varlist_begin();
547 auto ISrcRef = C->source_exprs().begin();
548 auto IDestRef = C->destination_exprs().begin();
549 for (auto *AssignOp : C->assignment_ops()) {
550 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000551 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000552 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000553 // Get the address of the master variable. If we are emitting code with
554 // TLS support, the address is passed from the master as field in the
555 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000556 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000557 if (getLangOpts().OpenMPUseTLS &&
558 getContext().getTargetInfo().isTLSSupported()) {
559 assert(CapturedStmtInfo->lookup(VD) &&
560 "Copyin threadprivates should have been captured!");
561 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
562 VK_LValue, (*IRef)->getExprLoc());
563 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000564 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000565 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000566 MasterAddr =
567 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
568 : CGM.GetAddrOfGlobal(VD),
569 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000570 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000571 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000572 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000573 if (CopiedVars.size() == 1) {
574 // At first check if current thread is a master thread. If it is, no
575 // need to copy data.
576 CopyBegin = createBasicBlock("copyin.not.master");
577 CopyEnd = createBasicBlock("copyin.not.master.end");
578 Builder.CreateCondBr(
579 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000580 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
581 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000582 CopyBegin, CopyEnd);
583 EmitBlock(CopyBegin);
584 }
585 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
586 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000587 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000588 }
589 ++IRef;
590 ++ISrcRef;
591 ++IDestRef;
592 }
593 }
594 if (CopyEnd) {
595 // Exit out of copying procedure for non-master thread.
596 EmitBlock(CopyEnd, /*IsFinished=*/true);
597 return true;
598 }
599 return false;
600}
601
Alexey Bataev38e89532015-04-16 04:54:05 +0000602bool CodeGenFunction::EmitOMPLastprivateClauseInit(
603 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000604 if (!HaveInsertPoint())
605 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000606 bool HasAtLeastOneLastprivate = false;
607 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000608 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000609 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000610 auto IRef = C->varlist_begin();
611 auto IDestRef = C->destination_exprs().begin();
612 for (auto *IInit : C->private_copies()) {
613 // Keep the address of the original variable for future update at the end
614 // of the loop.
615 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
616 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
617 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000618 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000619 DeclRefExpr DRE(
620 const_cast<VarDecl *>(OrigVD),
621 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
622 OrigVD) != nullptr,
623 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
624 return EmitLValue(&DRE).getAddress();
625 });
626 // Check if the variable is also a firstprivate: in this case IInit is
627 // not generated. Initialization of this variable will happen in codegen
628 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000629 if (IInit) {
630 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
631 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000632 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000633 // Emit private VarDecl with copy init.
634 EmitDecl(*VD);
635 return GetAddrOfLocalVar(VD);
636 });
637 assert(IsRegistered &&
638 "lastprivate var already registered as private");
639 (void)IsRegistered;
640 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000641 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000642 ++IRef;
643 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000644 }
645 }
646 return HasAtLeastOneLastprivate;
647}
648
649void CodeGenFunction::EmitOMPLastprivateClauseFinal(
650 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000651 if (!HaveInsertPoint())
652 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000653 // Emit following code:
654 // if (<IsLastIterCond>) {
655 // orig_var1 = private_orig_var1;
656 // ...
657 // orig_varn = private_orig_varn;
658 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000659 llvm::BasicBlock *ThenBB = nullptr;
660 llvm::BasicBlock *DoneBB = nullptr;
661 if (IsLastIterCond) {
662 ThenBB = createBasicBlock(".omp.lastprivate.then");
663 DoneBB = createBasicBlock(".omp.lastprivate.done");
664 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
665 EmitBlock(ThenBB);
666 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000667 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000668 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000669 auto IC = LoopDirective->counters().begin();
670 for (auto F : LoopDirective->finals()) {
671 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
672 LoopCountersAndUpdates[D] = F;
673 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000674 }
675 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000676 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
677 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
678 auto IRef = C->varlist_begin();
679 auto ISrcRef = C->source_exprs().begin();
680 auto IDestRef = C->destination_exprs().begin();
681 for (auto *AssignOp : C->assignment_ops()) {
682 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
683 QualType Type = PrivateVD->getType();
684 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
685 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
686 // If lastprivate variable is a loop control variable for loop-based
687 // directive, update its value before copyin back to original
688 // variable.
689 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
690 EmitIgnoredExpr(UpExpr);
691 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
692 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
693 // Get the address of the original variable.
694 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
695 // Get the address of the private variable.
696 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
697 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
698 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000699 Address(Builder.CreateLoad(PrivateAddr),
700 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000701 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000702 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000703 ++IRef;
704 ++ISrcRef;
705 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000706 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000707 if (auto *PostUpdate = C->getPostUpdateExpr())
708 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000709 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000710 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000711 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000712}
713
Alexey Bataev31300ed2016-02-04 11:27:03 +0000714static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
715 LValue BaseLV, llvm::Value *Addr) {
716 Address Tmp = Address::invalid();
717 Address TopTmp = Address::invalid();
718 Address MostTopTmp = Address::invalid();
719 BaseTy = BaseTy.getNonReferenceType();
720 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
721 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
722 Tmp = CGF.CreateMemTemp(BaseTy);
723 if (TopTmp.isValid())
724 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
725 else
726 MostTopTmp = Tmp;
727 TopTmp = Tmp;
728 BaseTy = BaseTy->getPointeeType();
729 }
730 llvm::Type *Ty = BaseLV.getPointer()->getType();
731 if (Tmp.isValid())
732 Ty = Tmp.getElementType();
733 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
734 if (Tmp.isValid()) {
735 CGF.Builder.CreateStore(Addr, Tmp);
736 return MostTopTmp;
737 }
738 return Address(Addr, BaseLV.getAlignment());
739}
740
741static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
742 LValue BaseLV) {
743 BaseTy = BaseTy.getNonReferenceType();
744 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
745 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
746 if (auto *PtrTy = BaseTy->getAs<PointerType>())
747 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
748 else {
749 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
750 BaseTy->castAs<ReferenceType>());
751 }
752 BaseTy = BaseTy->getPointeeType();
753 }
754 return CGF.MakeAddrLValue(
755 Address(
756 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
757 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
758 BaseLV.getAlignment()),
759 BaseLV.getType(), BaseLV.getAlignmentSource());
760}
761
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000762void CodeGenFunction::EmitOMPReductionClauseInit(
763 const OMPExecutableDirective &D,
764 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000765 if (!HaveInsertPoint())
766 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000767 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000768 auto ILHS = C->lhs_exprs().begin();
769 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000770 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000771 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000772 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000773 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
774 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
775 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
776 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
777 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
778 Base = TempOASE->getBase()->IgnoreParenImpCasts();
779 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
780 Base = TempASE->getBase()->IgnoreParenImpCasts();
781 auto *DE = cast<DeclRefExpr>(Base);
782 auto *OrigVD = cast<VarDecl>(DE->getDecl());
783 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
784 auto OASELValueUB =
785 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
786 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000787 LValue BaseLValue =
788 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
789 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000790 // Store the address of the original variable associated with the LHS
791 // implicit variable.
792 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
793 return OASELValueLB.getAddress();
794 });
795 // Emit reduction copy.
796 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000797 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
798 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000799 // Emit VarDecl with copy init for arrays.
800 // Get the address of the original variable captured in current
801 // captured region.
802 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
803 OASELValueLB.getPointer());
804 Size = Builder.CreateNUWAdd(
805 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
806 CodeGenFunction::OpaqueValueMapping OpaqueMap(
807 *this, cast<OpaqueValueExpr>(
808 getContext()
809 .getAsVariableArrayType(PrivateVD->getType())
810 ->getSizeExpr()),
811 RValue::get(Size));
812 EmitVariablyModifiedType(PrivateVD->getType());
813 auto Emission = EmitAutoVarAlloca(*PrivateVD);
814 auto Addr = Emission.getAllocatedAddress();
815 auto *Init = PrivateVD->getInit();
816 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
817 EmitAutoVarCleanups(Emission);
818 // Emit private VarDecl with reduction init.
819 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
820 OASELValueLB.getPointer());
821 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000822 return castToBase(*this, OrigVD->getType(),
823 OASELValueLB.getType(), OriginalBaseLValue,
824 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000825 });
826 assert(IsRegistered && "private var already registered as private");
827 // Silence the warning about unused variable.
828 (void)IsRegistered;
829 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
830 return GetAddrOfLocalVar(PrivateVD);
831 });
832 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
833 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
834 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
835 Base = TempASE->getBase()->IgnoreParenImpCasts();
836 auto *DE = cast<DeclRefExpr>(Base);
837 auto *OrigVD = cast<VarDecl>(DE->getDecl());
838 auto ASELValue = EmitLValue(ASE);
839 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000840 LValue BaseLValue = loadToBegin(
841 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000842 // Store the address of the original variable associated with the LHS
843 // implicit variable.
844 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
845 return ASELValue.getAddress();
846 });
847 // Emit reduction copy.
848 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000849 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000850 OriginalBaseLValue]() -> Address {
851 // Emit private VarDecl with reduction init.
852 EmitDecl(*PrivateVD);
853 auto Addr = GetAddrOfLocalVar(PrivateVD);
854 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
855 ASELValue.getPointer());
856 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000857 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
858 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 });
860 assert(IsRegistered && "private var already registered as private");
861 // Silence the warning about unused variable.
862 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000863 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
864 return Builder.CreateElementBitCast(
865 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
866 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000867 });
868 } else {
869 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000870 QualType Type = PrivateVD->getType();
871 if (getContext().getAsArrayType(Type)) {
872 // Store the address of the original variable associated with the LHS
873 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000874 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
875 CapturedStmtInfo->lookup(OrigVD) != nullptr,
876 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000877 Address OriginalAddr = EmitLValue(&DRE).getAddress();
878 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
879 LHSVD]() -> Address {
880 return Builder.CreateElementBitCast(
881 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
882 "lhs.begin");
883 });
884 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
885 if (Type->isVariablyModifiedType()) {
886 CodeGenFunction::OpaqueValueMapping OpaqueMap(
887 *this, cast<OpaqueValueExpr>(
888 getContext()
889 .getAsVariableArrayType(PrivateVD->getType())
890 ->getSizeExpr()),
891 RValue::get(
892 getTypeSize(OrigVD->getType().getNonReferenceType())));
893 EmitVariablyModifiedType(Type);
894 }
895 auto Emission = EmitAutoVarAlloca(*PrivateVD);
896 auto Addr = Emission.getAllocatedAddress();
897 auto *Init = PrivateVD->getInit();
898 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
899 EmitAutoVarCleanups(Emission);
900 return Emission.getAllocatedAddress();
901 });
902 assert(IsRegistered && "private var already registered as private");
903 // Silence the warning about unused variable.
904 (void)IsRegistered;
905 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
906 return Builder.CreateElementBitCast(
907 GetAddrOfLocalVar(PrivateVD),
908 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
909 });
910 } else {
911 // Store the address of the original variable associated with the LHS
912 // implicit variable.
913 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
914 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
915 CapturedStmtInfo->lookup(OrigVD) != nullptr,
916 IRef->getType(), VK_LValue, IRef->getExprLoc());
917 return EmitLValue(&DRE).getAddress();
918 });
919 // Emit reduction copy.
920 bool IsRegistered =
921 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
922 // Emit private VarDecl with reduction init.
923 EmitDecl(*PrivateVD);
924 return GetAddrOfLocalVar(PrivateVD);
925 });
926 assert(IsRegistered && "private var already registered as private");
927 // Silence the warning about unused variable.
928 (void)IsRegistered;
929 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
930 return GetAddrOfLocalVar(PrivateVD);
931 });
932 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000933 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000934 ++ILHS;
935 ++IRHS;
936 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000937 }
938 }
939}
940
941void CodeGenFunction::EmitOMPReductionClauseFinal(
942 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000943 if (!HaveInsertPoint())
944 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000945 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000946 llvm::SmallVector<const Expr *, 8> LHSExprs;
947 llvm::SmallVector<const Expr *, 8> RHSExprs;
948 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000949 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000950 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000951 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000952 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000953 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
954 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
955 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
956 }
957 if (HasAtLeastOneReduction) {
958 // Emit nowait reduction if nowait clause is present or directive is a
959 // parallel directive (it always has implicit barrier).
960 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000961 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000963 isOpenMPParallelDirective(D.getDirectiveKind()) ||
964 D.getDirectiveKind() == OMPD_simd,
965 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000966 }
967}
968
Alexey Bataev61205072016-03-02 04:57:40 +0000969static void emitPostUpdateForReductionClause(
970 CodeGenFunction &CGF, const OMPExecutableDirective &D,
971 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
972 if (!CGF.HaveInsertPoint())
973 return;
974 llvm::BasicBlock *DoneBB = nullptr;
975 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
976 if (auto *PostUpdate = C->getPostUpdateExpr()) {
977 if (!DoneBB) {
978 if (auto *Cond = CondGen(CGF)) {
979 // If the first post-update expression is found, emit conditional
980 // block if it was requested.
981 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
982 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
983 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
984 CGF.EmitBlock(ThenBB);
985 }
986 }
987 CGF.EmitIgnoredExpr(PostUpdate);
988 }
989 }
990 if (DoneBB)
991 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
992}
993
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000994static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
995 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000996 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000997 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000998 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000999 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1000 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001001 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1002 emitParallelOrTeamsOutlinedFunction(S,
1003 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001004 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001005 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001006 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1007 /*IgnoreResultAssign*/ true);
1008 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1009 CGF, NumThreads, NumThreadsClause->getLocStart());
1010 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001011 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +00001012 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001013 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1014 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1015 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001016 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001017 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1018 if (C->getNameModifier() == OMPD_unknown ||
1019 C->getNameModifier() == OMPD_parallel) {
1020 IfCond = C->getCondition();
1021 break;
1022 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001023 }
1024 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001025 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001026}
1027
1028void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001029 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001030 // Emit parallel region as a standalone region.
1031 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1032 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001033 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001034 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1035 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001036 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001037 // propagation master's thread values of threadprivate variables to local
1038 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001039 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1040 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1041 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001042 }
1043 CGF.EmitOMPPrivateClause(S, PrivateScope);
1044 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1045 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001046 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001047 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001048 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001049 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001050 emitPostUpdateForReductionClause(
1051 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001052}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001053
Alexey Bataev0f34da12015-07-02 04:17:07 +00001054void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1055 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056 RunCleanupsScope BodyScope(*this);
1057 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001058 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001059 EmitIgnoredExpr(I);
1060 }
Alexander Musman3276a272015-03-21 10:12:56 +00001061 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001062 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001063 for (auto U : C->updates()) {
1064 EmitIgnoredExpr(U);
1065 }
1066 }
1067
Alexander Musmana5f070a2014-10-01 06:03:56 +00001068 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001069 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001070 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001071 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001072 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001073 // The end (updates/cleanups).
1074 EmitBlock(Continue.getBlock());
1075 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001076}
1077
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001078void CodeGenFunction::EmitOMPInnerLoop(
1079 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1080 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001081 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1082 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001083 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001084
1085 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001086 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001087 EmitBlock(CondBlock);
1088 LoopStack.push(CondBlock);
1089
1090 // If there are any cleanups between here and the loop-exit scope,
1091 // create a block to stage a loop exit along.
1092 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001093 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001094 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001095
Alexander Musmand196ef22014-10-07 08:57:09 +00001096 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001097
Alexey Bataev2df54a02015-03-12 08:53:29 +00001098 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001099 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001100 if (ExitBlock != LoopExit.getBlock()) {
1101 EmitBlock(ExitBlock);
1102 EmitBranchThroughCleanup(LoopExit);
1103 }
1104
1105 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001106 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001107
1108 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001109 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001110 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1111
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001112 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001113
1114 // Emit "IV = IV + 1" and a back-edge to the condition block.
1115 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001116 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001117 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001118 BreakContinueStack.pop_back();
1119 EmitBranch(CondBlock);
1120 LoopStack.pop();
1121 // Emit the fall-through block.
1122 EmitBlock(LoopExit.getBlock());
1123}
1124
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001125void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001126 if (!HaveInsertPoint())
1127 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001128 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001129 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001130 for (auto Init : C->inits()) {
1131 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001132 auto *OrigVD = cast<VarDecl>(
1133 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1134 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1135 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1136 VD->getInit()->getType(), VK_LValue,
1137 VD->getInit()->getExprLoc());
1138 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1139 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001140 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001141 /*capturedByInit=*/false);
1142 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001143 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001144 // Emit the linear steps for the linear clauses.
1145 // If a step is not constant, it is pre-calculated before the loop.
1146 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1147 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001148 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001149 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001150 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001151 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001152 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001153}
1154
1155static void emitLinearClauseFinal(CodeGenFunction &CGF,
1156 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001157 if (!CGF.HaveInsertPoint())
1158 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001159 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001160 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001161 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001162 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001163 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1164 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001165 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001166 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001167 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001168 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001169 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001170 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001171 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001172 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001173 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001174 }
1175 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001176}
1177
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001178static void emitAlignedClause(CodeGenFunction &CGF,
1179 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001180 if (!CGF.HaveInsertPoint())
1181 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001182 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001183 unsigned ClauseAlignment = 0;
1184 if (auto AlignmentExpr = Clause->getAlignment()) {
1185 auto AlignmentCI =
1186 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1187 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001188 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001189 for (auto E : Clause->varlists()) {
1190 unsigned Alignment = ClauseAlignment;
1191 if (Alignment == 0) {
1192 // OpenMP [2.8.1, Description]
1193 // If no optional parameter is specified, implementation-defined default
1194 // alignments for SIMD instructions on the target platforms are assumed.
1195 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001196 CGF.getContext()
1197 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1198 E->getType()->getPointeeType()))
1199 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001200 }
1201 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1202 "alignment is not power of 2");
1203 if (Alignment != 0) {
1204 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1205 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1206 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001207 }
1208 }
1209}
1210
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001211static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001212 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001213 ArrayRef<Expr *> Counters,
1214 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001215 if (!CGF.HaveInsertPoint())
1216 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001217 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001218 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001219 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1220 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001221 Address Addr = Address::invalid();
1222 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001223 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001224 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001225 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001226 Addr = VarEmission.getAllocatedAddress();
1227 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001228 });
John McCall7f416cc2015-09-08 08:05:57 +00001229 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001230 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001231 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001232}
1233
Alexey Bataev62dbb972015-04-22 11:59:37 +00001234static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1235 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1236 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001237 if (!CGF.HaveInsertPoint())
1238 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001239 {
1240 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001241 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1242 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001243 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001244 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001245 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001246 CGF.EmitIgnoredExpr(I);
1247 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001248 }
1249 // Check that loop is executed at least one time.
1250 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1251}
1252
Alexander Musman3276a272015-03-21 10:12:56 +00001253static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001254emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001255 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001256 if (!CGF.HaveInsertPoint())
1257 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001258 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001259 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001260 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001261 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1262 auto *PrivateVD =
1263 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001264 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001265 // Emit private VarDecl with copy init.
1266 CGF.EmitVarDecl(*PrivateVD);
1267 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001268 });
1269 assert(IsRegistered && "linear var already registered as private");
1270 // Silence the warning about unused variable.
1271 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001272 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001273 }
1274 }
1275}
1276
Alexey Bataev45bfad52015-08-21 12:19:04 +00001277static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001278 const OMPExecutableDirective &D,
1279 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001280 if (!CGF.HaveInsertPoint())
1281 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001282 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001283 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1284 /*ignoreResult=*/true);
1285 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1286 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1287 // In presence of finite 'safelen', it may be unsafe to mark all
1288 // the memory instructions parallel, because loop-carried
1289 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001290 if (!IsMonotonic)
1291 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001292 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001293 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1294 /*ignoreResult=*/true);
1295 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001296 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001297 // In presence of finite 'safelen', it may be unsafe to mark all
1298 // the memory instructions parallel, because loop-carried
1299 // dependences of 'safelen' iterations are possible.
1300 CGF.LoopStack.setParallel(false);
1301 }
1302}
1303
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001304void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1305 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001306 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001307 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001308 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001309 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310}
1311
1312void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001313 if (!HaveInsertPoint())
1314 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001315 auto IC = D.counters().begin();
1316 for (auto F : D.finals()) {
1317 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001318 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001319 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1320 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1321 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001322 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001323 OMPPrivateScope VarScope(*this);
1324 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001325 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001326 (void)VarScope.Privatize();
1327 EmitIgnoredExpr(F);
1328 }
1329 ++IC;
1330 }
1331 emitLinearClauseFinal(*this, D);
1332}
1333
Alexander Musman515ad8c2014-05-22 08:54:05 +00001334void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001335 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001336 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001337 // for (IV in 0..LastIteration) BODY;
1338 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001339 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001340 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001341
Alexey Bataev62dbb972015-04-22 11:59:37 +00001342 // Emit: if (PreCond) - begin.
1343 // If the condition constant folds and can be elided, avoid emitting the
1344 // whole loop.
1345 bool CondConstant;
1346 llvm::BasicBlock *ContBlock = nullptr;
1347 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1348 if (!CondConstant)
1349 return;
1350 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001351 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1352 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001353 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1354 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001355 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001356 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001357 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001358
1359 // Emit the loop iteration variable.
1360 const Expr *IVExpr = S.getIterationVariable();
1361 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1362 CGF.EmitVarDecl(*IVDecl);
1363 CGF.EmitIgnoredExpr(S.getInit());
1364
1365 // Emit the iterations count variable.
1366 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001367 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001368 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1369 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1370 // Emit calculation of the iterations count.
1371 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001372 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001373
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001374 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001375
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001376 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001377 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001378 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001379 {
1380 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001381 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1382 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001383 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001384 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001385 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001386 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001387 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001388 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1389 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001390 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001391 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001392 CGF.EmitStopPoint(&S);
1393 },
1394 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001395 // Emit final copy of the lastprivate variables at the end of loops.
1396 if (HasLastprivateClause) {
1397 CGF.EmitOMPLastprivateClauseFinal(S);
1398 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001399 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001400 emitPostUpdateForReductionClause(
1401 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001402 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001403 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001404 // Emit: if (PreCond) - end.
1405 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001406 CGF.EmitBranch(ContBlock);
1407 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001408 }
1409 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001410 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001411}
1412
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001413void CodeGenFunction::EmitOMPForOuterLoop(
1414 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1415 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1416 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001417 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001418
1419 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001420 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001421
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001422 assert((Ordered ||
1423 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001424 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001425
1426 // Emit outer loop.
1427 //
1428 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001429 // When schedule(dynamic,chunk_size) is specified, the iterations are
1430 // distributed to threads in the team in chunks as the threads request them.
1431 // Each thread executes a chunk of iterations, then requests another chunk,
1432 // until no chunks remain to be distributed. Each chunk contains chunk_size
1433 // iterations, except for the last chunk to be distributed, which may have
1434 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1435 //
1436 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1437 // to threads in the team in chunks as the executing threads request them.
1438 // Each thread executes a chunk of iterations, then requests another chunk,
1439 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1440 // each chunk is proportional to the number of unassigned iterations divided
1441 // by the number of threads in the team, decreasing to 1. For a chunk_size
1442 // with value k (greater than 1), the size of each chunk is determined in the
1443 // same way, with the restriction that the chunks do not contain fewer than k
1444 // iterations (except for the last chunk to be assigned, which may have fewer
1445 // than k iterations).
1446 //
1447 // When schedule(auto) is specified, the decision regarding scheduling is
1448 // delegated to the compiler and/or runtime system. The programmer gives the
1449 // implementation the freedom to choose any possible mapping of iterations to
1450 // threads in the team.
1451 //
1452 // When schedule(runtime) is specified, the decision regarding scheduling is
1453 // deferred until run time, and the schedule and chunk size are taken from the
1454 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1455 // implementation defined
1456 //
1457 // while(__kmpc_dispatch_next(&LB, &UB)) {
1458 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001459 // while (idx <= UB) { BODY; ++idx;
1460 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1461 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001462 // }
1463 //
1464 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001465 // When schedule(static, chunk_size) is specified, iterations are divided into
1466 // chunks of size chunk_size, and the chunks are assigned to the threads in
1467 // the team in a round-robin fashion in the order of the thread number.
1468 //
1469 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1470 // while (idx <= UB) { BODY; ++idx; } // inner loop
1471 // LB = LB + ST;
1472 // UB = UB + ST;
1473 // }
1474 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001475
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001476 const Expr *IVExpr = S.getIterationVariable();
1477 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1478 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1479
John McCall7f416cc2015-09-08 08:05:57 +00001480 if (DynamicOrOrdered) {
1481 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1482 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1483 IVSize, IVSigned, Ordered, UBVal, Chunk);
1484 } else {
1485 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1486 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1487 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001488
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001489 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1490
1491 // Start the loop with a block that tests the condition.
1492 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1493 EmitBlock(CondBlock);
1494 LoopStack.push(CondBlock);
1495
1496 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001497 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001498 // UB = min(UB, GlobalUB)
1499 EmitIgnoredExpr(S.getEnsureUpperBound());
1500 // IV = LB
1501 EmitIgnoredExpr(S.getInit());
1502 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001503 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001504 } else {
1505 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1506 IL, LB, UB, ST);
1507 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001508
1509 // If there are any cleanups between here and the loop-exit scope,
1510 // create a block to stage a loop exit along.
1511 auto ExitBlock = LoopExit.getBlock();
1512 if (LoopScope.requiresCleanups())
1513 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1514
1515 auto LoopBody = createBasicBlock("omp.dispatch.body");
1516 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1517 if (ExitBlock != LoopExit.getBlock()) {
1518 EmitBlock(ExitBlock);
1519 EmitBranchThroughCleanup(LoopExit);
1520 }
1521 EmitBlock(LoopBody);
1522
Alexander Musman92bdaab2015-03-12 13:37:50 +00001523 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1524 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001525 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001526 EmitIgnoredExpr(S.getInit());
1527
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001528 // Create a block for the increment.
1529 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1530 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1531
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001532 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1533 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001534 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1535 LoopStack.setParallel(!IsMonotonic);
1536 else
1537 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001538
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001539 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001540 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1541 [&S, LoopExit](CodeGenFunction &CGF) {
1542 CGF.EmitOMPLoopBody(S, LoopExit);
1543 CGF.EmitStopPoint(&S);
1544 },
1545 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1546 if (Ordered) {
1547 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1548 CGF, Loc, IVSize, IVSigned);
1549 }
1550 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001551
1552 EmitBlock(Continue.getBlock());
1553 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001554 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001555 // Emit "LB = LB + Stride", "UB = UB + Stride".
1556 EmitIgnoredExpr(S.getNextLowerBound());
1557 EmitIgnoredExpr(S.getNextUpperBound());
1558 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001559
1560 EmitBranch(CondBlock);
1561 LoopStack.pop();
1562 // Emit the fall-through block.
1563 EmitBlock(LoopExit.getBlock());
1564
1565 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001566 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001567 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001568}
1569
Alexander Musmanc6388682014-12-15 07:07:06 +00001570/// \brief Emit a helper variable and return corresponding lvalue.
1571static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1572 const DeclRefExpr *Helper) {
1573 auto VDecl = cast<VarDecl>(Helper->getDecl());
1574 CGF.EmitVarDecl(*VDecl);
1575 return CGF.EmitLValue(Helper);
1576}
1577
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001578namespace {
1579 struct ScheduleKindModifiersTy {
1580 OpenMPScheduleClauseKind Kind;
1581 OpenMPScheduleClauseModifier M1;
1582 OpenMPScheduleClauseModifier M2;
1583 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1584 OpenMPScheduleClauseModifier M1,
1585 OpenMPScheduleClauseModifier M2)
1586 : Kind(Kind), M1(M1), M2(M2) {}
1587 };
1588} // namespace
1589
Alexey Bataev38e89532015-04-16 04:54:05 +00001590bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001591 // Emit the loop iteration variable.
1592 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1593 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1594 EmitVarDecl(*IVDecl);
1595
1596 // Emit the iterations count variable.
1597 // If it is not a variable, Sema decided to calculate iterations count on each
1598 // iteration (e.g., it is foldable into a constant).
1599 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1600 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1601 // Emit calculation of the iterations count.
1602 EmitIgnoredExpr(S.getCalcLastIteration());
1603 }
1604
1605 auto &RT = CGM.getOpenMPRuntime();
1606
Alexey Bataev38e89532015-04-16 04:54:05 +00001607 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001608 // Check pre-condition.
1609 {
1610 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001611 // If the condition constant folds and can be elided, avoid emitting the
1612 // whole loop.
1613 bool CondConstant;
1614 llvm::BasicBlock *ContBlock = nullptr;
1615 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1616 if (!CondConstant)
1617 return false;
1618 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001619 auto *ThenBlock = createBasicBlock("omp.precond.then");
1620 ContBlock = createBasicBlock("omp.precond.end");
1621 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001622 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001623 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001624 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001625 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001626
1627 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001628 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001629 // Emit 'then' code.
1630 {
1631 // Emit helper vars inits.
1632 LValue LB =
1633 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1634 LValue UB =
1635 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1636 LValue ST =
1637 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1638 LValue IL =
1639 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1640
1641 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001642 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1643 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001644 // initialization of firstprivate variables and post-update of
1645 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001646 CGM.getOpenMPRuntime().emitBarrierCall(
1647 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1648 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001649 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001650 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001651 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001652 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001653 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1654 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001655 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001656 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001657
1658 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001659 llvm::Value *Chunk = nullptr;
1660 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1661 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1662 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1663 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1664 ScheduleKind = C->getScheduleKind();
1665 M1 = C->getFirstScheduleModifier();
1666 M2 = C->getSecondScheduleModifier();
1667 if (const auto *Ch = C->getChunkSize()) {
1668 Chunk = EmitScalarExpr(Ch);
1669 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1670 S.getIterationVariable()->getType(),
1671 S.getLocStart());
1672 }
1673 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001674 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1675 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001676 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001677 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1678 // If the static schedule kind is specified or if the ordered clause is
1679 // specified, and if no monotonic modifier is specified, the effect will
1680 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001681 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001682 /* Chunked */ Chunk != nullptr) &&
1683 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001684 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1685 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001686 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1687 // When no chunk_size is specified, the iteration space is divided into
1688 // chunks that are approximately equal in size, and at most one chunk is
1689 // distributed to each thread. Note that the size of the chunks is
1690 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001691 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1692 IVSize, IVSigned, Ordered,
1693 IL.getAddress(), LB.getAddress(),
1694 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001695 auto LoopExit =
1696 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001697 // UB = min(UB, GlobalUB);
1698 EmitIgnoredExpr(S.getEnsureUpperBound());
1699 // IV = LB;
1700 EmitIgnoredExpr(S.getInit());
1701 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001702 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1703 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001704 [&S, LoopExit](CodeGenFunction &CGF) {
1705 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001706 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001707 },
1708 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001709 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001710 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001711 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001712 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001713 const bool IsMonotonic = Ordered ||
1714 ScheduleKind == OMPC_SCHEDULE_static ||
1715 ScheduleKind == OMPC_SCHEDULE_unknown ||
1716 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1717 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001718 // Emit the outer loop, which requests its work chunk [LB..UB] from
1719 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001720 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001721 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1722 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001723 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001724 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001725 // Emit post-update of the reduction variables if IsLastIter != 0.
1726 emitPostUpdateForReductionClause(
1727 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1728 return CGF.Builder.CreateIsNotNull(
1729 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1730 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001731 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1732 if (HasLastprivateClause)
1733 EmitOMPLastprivateClauseFinal(
1734 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001735 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001736 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1737 EmitOMPSimdFinal(S);
1738 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001739 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001740 if (ContBlock) {
1741 EmitBranch(ContBlock);
1742 EmitBlock(ContBlock, true);
1743 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001744 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001745 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001746}
1747
1748void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001749 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001750 {
1751 OMPLexicalScope Scope(*this, S);
1752 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1753 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1754 };
1755 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1756 S.hasCancel());
1757 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001758
1759 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001760 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001761 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1762 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001763}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001764
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001765void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001766 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001767 {
1768 OMPLexicalScope Scope(*this, S);
1769 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1770 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1771 };
1772 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1773 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001774
1775 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001776 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001777 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1778 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001779}
1780
Alexey Bataev2df54a02015-03-12 08:53:29 +00001781static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1782 const Twine &Name,
1783 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001784 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001785 if (Init)
1786 CGF.EmitScalarInit(Init, LVal);
1787 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001788}
1789
Alexey Bataev3392d762016-02-16 11:18:12 +00001790void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001791 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1792 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001793 bool HasLastprivates = false;
1794 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1795 auto &C = CGF.CGM.getContext();
1796 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1797 // Emit helper vars inits.
1798 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1799 CGF.Builder.getInt32(0));
1800 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1801 : CGF.Builder.getInt32(0);
1802 LValue UB =
1803 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1804 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1805 CGF.Builder.getInt32(1));
1806 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1807 CGF.Builder.getInt32(0));
1808 // Loop counter.
1809 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1810 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1811 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1812 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1813 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1814 // Generate condition for loop.
1815 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1816 OK_Ordinary, S.getLocStart(),
1817 /*fpContractable=*/false);
1818 // Increment for loop counter.
1819 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1820 S.getLocStart());
1821 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1822 // Iterate through all sections and emit a switch construct:
1823 // switch (IV) {
1824 // case 0:
1825 // <SectionStmt[0]>;
1826 // break;
1827 // ...
1828 // case <NumSection> - 1:
1829 // <SectionStmt[<NumSection> - 1]>;
1830 // break;
1831 // }
1832 // .omp.sections.exit:
1833 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1834 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1835 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1836 CS == nullptr ? 1 : CS->size());
1837 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001838 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001839 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001840 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1841 CGF.EmitBlock(CaseBB);
1842 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001843 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001844 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001845 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001846 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001847 } else {
1848 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1849 CGF.EmitBlock(CaseBB);
1850 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1851 CGF.EmitStmt(Stmt);
1852 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001853 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001854 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001855 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001856
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001857 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1858 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001859 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001860 // initialization of firstprivate variables and post-update of lastprivate
1861 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001862 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1863 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1864 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001865 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001866 CGF.EmitOMPPrivateClause(S, LoopScope);
1867 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1868 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1869 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001870
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001871 // Emit static non-chunked loop.
1872 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1873 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1874 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1875 UB.getAddress(), ST.getAddress());
1876 // UB = min(UB, GlobalUB);
1877 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1878 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1879 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1880 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1881 // IV = LB;
1882 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1883 // while (idx <= UB) { BODY; ++idx; }
1884 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1885 [](CodeGenFunction &) {});
1886 // Tell the runtime we are done.
1887 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1888 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001889 // Emit post-update of the reduction variables if IsLastIter != 0.
1890 emitPostUpdateForReductionClause(
1891 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1892 return CGF.Builder.CreateIsNotNull(
1893 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1894 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001895
1896 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1897 if (HasLastprivates)
1898 CGF.EmitOMPLastprivateClauseFinal(
1899 S, CGF.Builder.CreateIsNotNull(
1900 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001901 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001902
1903 bool HasCancel = false;
1904 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1905 HasCancel = OSD->hasCancel();
1906 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1907 HasCancel = OPSD->hasCancel();
1908 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1909 HasCancel);
1910 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1911 // clause. Otherwise the barrier will be generated by the codegen for the
1912 // directive.
1913 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001914 // Emit implicit barrier to synchronize threads and avoid data races on
1915 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001916 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1917 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001918 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001919}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001920
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001921void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001922 {
1923 OMPLexicalScope Scope(*this, S);
1924 EmitSections(S);
1925 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001926 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001927 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001928 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1929 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001930 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001931}
1932
1933void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001934 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001935 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1936 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001937 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001938 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1939 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001940}
1941
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001942void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001943 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001944 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001945 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001946 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001947 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001948 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001949 // Build a list of copyprivate variables along with helper expressions
1950 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001951 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001952 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001953 DestExprs.append(C->destination_exprs().begin(),
1954 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001955 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001956 AssignmentOps.append(C->assignment_ops().begin(),
1957 C->assignment_ops().end());
1958 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001959 {
1960 OMPLexicalScope Scope(*this, S);
1961 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001962 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001963 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001964 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001965 CGF.EmitOMPPrivateClause(S, SingleScope);
1966 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001967 CGF.EmitStmt(
1968 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1969 };
1970 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1971 CopyprivateVars, DestExprs,
1972 SrcExprs, AssignmentOps);
1973 }
1974 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1975 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00001976 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001977 CGM.getOpenMPRuntime().emitBarrierCall(
1978 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001979 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001980 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001981}
1982
Alexey Bataev8d690652014-12-04 07:23:53 +00001983void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001984 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001985 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1986 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001987 };
1988 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001989}
1990
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001991void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001992 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001993 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1994 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001995 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001996 Expr *Hint = nullptr;
1997 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1998 Hint = HintClause->getHint();
1999 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2000 S.getDirectiveName().getAsString(),
2001 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002002}
2003
Alexey Bataev671605e2015-04-13 05:28:11 +00002004void CodeGenFunction::EmitOMPParallelForDirective(
2005 const OMPParallelForDirective &S) {
2006 // Emit directive as a combined directive that consists of two implicit
2007 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002008 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002009 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2010 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002011 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002012 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002013}
2014
Alexander Musmane4e893b2014-09-23 09:33:00 +00002015void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002016 const OMPParallelForSimdDirective &S) {
2017 // Emit directive as a combined directive that consists of two implicit
2018 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002019 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002020 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2021 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002022 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002023 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002024}
2025
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002026void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002027 const OMPParallelSectionsDirective &S) {
2028 // Emit directive as a combined directive that consists of two implicit
2029 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002030 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002031 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002032 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002033}
2034
Alexey Bataev62b63b12015-03-10 07:28:44 +00002035void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2036 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002037 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002038 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2039 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2040 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002041 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002042 // The first function argument for tasks is a thread id, the second one is a
2043 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002044 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2045 // Get list of private variables.
2046 llvm::SmallVector<const Expr *, 8> PrivateVars;
2047 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002048 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002049 auto IRef = C->varlist_begin();
2050 for (auto *IInit : C->private_copies()) {
2051 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2052 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2053 PrivateVars.push_back(*IRef);
2054 PrivateCopies.push_back(IInit);
2055 }
2056 ++IRef;
2057 }
2058 }
2059 EmittedAsPrivate.clear();
2060 // Get list of firstprivate variables.
2061 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2062 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2063 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002064 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002065 auto IRef = C->varlist_begin();
2066 auto IElemInitRef = C->inits().begin();
2067 for (auto *IInit : C->private_copies()) {
2068 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2069 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2070 FirstprivateVars.push_back(*IRef);
2071 FirstprivateCopies.push_back(IInit);
2072 FirstprivateInits.push_back(*IElemInitRef);
2073 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002074 ++IRef;
2075 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002076 }
2077 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002078 // Build list of dependences.
2079 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2080 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002081 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002082 for (auto *IRef : C->varlists()) {
2083 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2084 }
2085 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002086 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2087 CodeGenFunction &CGF) {
2088 // Set proper addresses for generated private copies.
2089 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2090 OMPPrivateScope Scope(CGF);
2091 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002092 auto *CopyFn = CGF.Builder.CreateLoad(
2093 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2094 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2095 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002096 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002097 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002098 PrivatePtrs;
2099 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2100 CallArgs.push_back(PrivatesPtr);
2101 for (auto *E : PrivateVars) {
2102 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002103 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002104 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2105 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002106 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002107 }
2108 for (auto *E : FirstprivateVars) {
2109 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002110 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002111 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2112 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002113 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002114 }
2115 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2116 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002117 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2118 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002119 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2120 }
2121 }
2122 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002123 if (*PartId) {
2124 // TODO: emit code for untied tasks.
2125 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002126 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002127 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002128 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2129 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002130 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002131 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002132 // Check if the task is final
2133 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002134 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002135 // If the condition constant folds and can be elided, try to avoid emitting
2136 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002137 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002138 bool CondConstant;
2139 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2140 Final.setInt(CondConstant);
2141 else
2142 Final.setPointer(EvaluateExprAsBool(Cond));
2143 } else {
2144 // By default the task is not final.
2145 Final.setInt(/*IntVal=*/false);
2146 }
2147 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002148 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002149 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2150 if (C->getNameModifier() == OMPD_unknown ||
2151 C->getNameModifier() == OMPD_task) {
2152 IfCond = C->getCondition();
2153 break;
2154 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002155 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002156 CGM.getOpenMPRuntime().emitTaskCall(
2157 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002158 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002159 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002160}
2161
Alexey Bataev9f797f32015-02-05 05:57:51 +00002162void CodeGenFunction::EmitOMPTaskyieldDirective(
2163 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002164 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002165}
2166
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002167void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002168 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002169}
2170
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002171void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2172 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002173}
2174
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002175void CodeGenFunction::EmitOMPTaskgroupDirective(
2176 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002177 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002178 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2179 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002180 };
2181 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2182}
2183
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002184void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002185 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002186 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002187 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2188 FlushClause->varlist_end());
2189 }
2190 return llvm::None;
2191 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002192}
2193
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002194void CodeGenFunction::EmitOMPDistributeDirective(
2195 const OMPDistributeDirective &S) {
2196 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2197}
2198
Alexey Bataev5f600d62015-09-29 03:48:57 +00002199static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2200 const CapturedStmt *S) {
2201 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2202 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2203 CGF.CapturedStmtInfo = &CapStmtInfo;
2204 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2205 Fn->addFnAttr(llvm::Attribute::NoInline);
2206 return Fn;
2207}
2208
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002209void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002210 if (!S.getAssociatedStmt())
2211 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002212 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002213 auto *C = S.getSingleClause<OMPSIMDClause>();
2214 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2215 if (C) {
2216 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2217 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2218 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2219 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2220 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2221 } else {
2222 CGF.EmitStmt(
2223 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2224 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002225 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002226 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002227}
2228
Alexey Bataevb57056f2015-01-22 06:17:56 +00002229static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002230 QualType SrcType, QualType DestType,
2231 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002232 assert(CGF.hasScalarEvaluationKind(DestType) &&
2233 "DestType must have scalar evaluation kind.");
2234 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2235 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002236 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2237 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002238 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002239 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002240}
2241
2242static CodeGenFunction::ComplexPairTy
2243convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002244 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002245 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2246 "DestType must have complex evaluation kind.");
2247 CodeGenFunction::ComplexPairTy ComplexVal;
2248 if (Val.isScalar()) {
2249 // Convert the input element to the element type of the complex.
2250 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002251 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2252 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002253 ComplexVal = CodeGenFunction::ComplexPairTy(
2254 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2255 } else {
2256 assert(Val.isComplex() && "Must be a scalar or complex.");
2257 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2258 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2259 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002260 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002261 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002262 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002263 }
2264 return ComplexVal;
2265}
2266
Alexey Bataev5e018f92015-04-23 06:35:10 +00002267static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2268 LValue LVal, RValue RVal) {
2269 if (LVal.isGlobalReg()) {
2270 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2271 } else {
2272 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2273 : llvm::Monotonic,
2274 LVal.isVolatile(), /*IsInit=*/false);
2275 }
2276}
2277
Alexey Bataev8524d152016-01-21 12:35:58 +00002278void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2279 QualType RValTy, SourceLocation Loc) {
2280 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002281 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002282 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2283 *this, RVal, RValTy, LVal.getType(), Loc)),
2284 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002285 break;
2286 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002287 EmitStoreOfComplex(
2288 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002289 /*isInit=*/false);
2290 break;
2291 case TEK_Aggregate:
2292 llvm_unreachable("Must be a scalar or complex.");
2293 }
2294}
2295
Alexey Bataevb57056f2015-01-22 06:17:56 +00002296static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2297 const Expr *X, const Expr *V,
2298 SourceLocation Loc) {
2299 // v = x;
2300 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2301 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2302 LValue XLValue = CGF.EmitLValue(X);
2303 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002304 RValue Res = XLValue.isGlobalReg()
2305 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2306 : CGF.EmitAtomicLoad(XLValue, Loc,
2307 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002308 : llvm::Monotonic,
2309 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002310 // OpenMP, 2.12.6, atomic Construct
2311 // Any atomic construct with a seq_cst clause forces the atomically
2312 // performed operation to include an implicit flush operation without a
2313 // list.
2314 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002315 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002316 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002317}
2318
Alexey Bataevb8329262015-02-27 06:33:30 +00002319static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2320 const Expr *X, const Expr *E,
2321 SourceLocation Loc) {
2322 // x = expr;
2323 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002324 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002325 // OpenMP, 2.12.6, atomic Construct
2326 // Any atomic construct with a seq_cst clause forces the atomically
2327 // performed operation to include an implicit flush operation without a
2328 // list.
2329 if (IsSeqCst)
2330 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2331}
2332
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002333static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2334 RValue Update,
2335 BinaryOperatorKind BO,
2336 llvm::AtomicOrdering AO,
2337 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002338 auto &Context = CGF.CGM.getContext();
2339 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002340 // expression is simple and atomic is allowed for the given type for the
2341 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002342 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002343 !Update.getScalarVal()->getType()->isIntegerTy() ||
2344 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2345 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002346 X.getAddress().getElementType())) ||
2347 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002348 !Context.getTargetInfo().hasBuiltinAtomic(
2349 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002350 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002351
2352 llvm::AtomicRMWInst::BinOp RMWOp;
2353 switch (BO) {
2354 case BO_Add:
2355 RMWOp = llvm::AtomicRMWInst::Add;
2356 break;
2357 case BO_Sub:
2358 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002359 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002360 RMWOp = llvm::AtomicRMWInst::Sub;
2361 break;
2362 case BO_And:
2363 RMWOp = llvm::AtomicRMWInst::And;
2364 break;
2365 case BO_Or:
2366 RMWOp = llvm::AtomicRMWInst::Or;
2367 break;
2368 case BO_Xor:
2369 RMWOp = llvm::AtomicRMWInst::Xor;
2370 break;
2371 case BO_LT:
2372 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2373 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2374 : llvm::AtomicRMWInst::Max)
2375 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2376 : llvm::AtomicRMWInst::UMax);
2377 break;
2378 case BO_GT:
2379 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2380 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2381 : llvm::AtomicRMWInst::Min)
2382 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2383 : llvm::AtomicRMWInst::UMin);
2384 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002385 case BO_Assign:
2386 RMWOp = llvm::AtomicRMWInst::Xchg;
2387 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002388 case BO_Mul:
2389 case BO_Div:
2390 case BO_Rem:
2391 case BO_Shl:
2392 case BO_Shr:
2393 case BO_LAnd:
2394 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002395 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002396 case BO_PtrMemD:
2397 case BO_PtrMemI:
2398 case BO_LE:
2399 case BO_GE:
2400 case BO_EQ:
2401 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002402 case BO_AddAssign:
2403 case BO_SubAssign:
2404 case BO_AndAssign:
2405 case BO_OrAssign:
2406 case BO_XorAssign:
2407 case BO_MulAssign:
2408 case BO_DivAssign:
2409 case BO_RemAssign:
2410 case BO_ShlAssign:
2411 case BO_ShrAssign:
2412 case BO_Comma:
2413 llvm_unreachable("Unsupported atomic update operation");
2414 }
2415 auto *UpdateVal = Update.getScalarVal();
2416 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2417 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002418 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002419 X.getType()->hasSignedIntegerRepresentation());
2420 }
John McCall7f416cc2015-09-08 08:05:57 +00002421 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002422 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002423}
2424
Alexey Bataev5e018f92015-04-23 06:35:10 +00002425std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002426 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2427 llvm::AtomicOrdering AO, SourceLocation Loc,
2428 const llvm::function_ref<RValue(RValue)> &CommonGen) {
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 Bataev5e018f92015-04-23 06:35:10 +00002435 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2436 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002437 if (X.isGlobalReg()) {
2438 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2439 // 'xrval'.
2440 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2441 } else {
2442 // Perform compare-and-swap procedure.
2443 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002444 }
2445 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002446 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002447}
2448
2449static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2450 const Expr *X, const Expr *E,
2451 const Expr *UE, bool IsXLHSInRHSPart,
2452 SourceLocation Loc) {
2453 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2454 "Update expr in 'atomic update' must be a binary operator.");
2455 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2456 // Update expressions are allowed to have the following forms:
2457 // x binop= expr; -> xrval + expr;
2458 // x++, ++x -> xrval + 1;
2459 // x--, --x -> xrval - 1;
2460 // x = x binop expr; -> xrval binop expr
2461 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002462 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002463 LValue XLValue = CGF.EmitLValue(X);
2464 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002465 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002466 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2467 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2468 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2469 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2470 auto Gen =
2471 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2472 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2473 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2474 return CGF.EmitAnyExpr(UE);
2475 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002476 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2477 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2478 // OpenMP, 2.12.6, atomic Construct
2479 // Any atomic construct with a seq_cst clause forces the atomically
2480 // performed operation to include an implicit flush operation without a
2481 // list.
2482 if (IsSeqCst)
2483 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2484}
2485
2486static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002487 QualType SourceType, QualType ResType,
2488 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002489 switch (CGF.getEvaluationKind(ResType)) {
2490 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002491 return RValue::get(
2492 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002493 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002494 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002495 return RValue::getComplex(Res.first, Res.second);
2496 }
2497 case TEK_Aggregate:
2498 break;
2499 }
2500 llvm_unreachable("Must be a scalar or complex.");
2501}
2502
2503static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2504 bool IsPostfixUpdate, const Expr *V,
2505 const Expr *X, const Expr *E,
2506 const Expr *UE, bool IsXLHSInRHSPart,
2507 SourceLocation Loc) {
2508 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2509 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2510 RValue NewVVal;
2511 LValue VLValue = CGF.EmitLValue(V);
2512 LValue XLValue = CGF.EmitLValue(X);
2513 RValue ExprRValue = CGF.EmitAnyExpr(E);
2514 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2515 QualType NewVValType;
2516 if (UE) {
2517 // 'x' is updated with some additional value.
2518 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2519 "Update expr in 'atomic capture' must be a binary operator.");
2520 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2521 // Update expressions are allowed to have the following forms:
2522 // x binop= expr; -> xrval + expr;
2523 // x++, ++x -> xrval + 1;
2524 // x--, --x -> xrval - 1;
2525 // x = x binop expr; -> xrval binop expr
2526 // x = expr Op x; - > expr binop xrval;
2527 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2528 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2529 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2530 NewVValType = XRValExpr->getType();
2531 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2532 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2533 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2534 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2535 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2536 RValue Res = CGF.EmitAnyExpr(UE);
2537 NewVVal = IsPostfixUpdate ? XRValue : Res;
2538 return Res;
2539 };
2540 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2541 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2542 if (Res.first) {
2543 // 'atomicrmw' instruction was generated.
2544 if (IsPostfixUpdate) {
2545 // Use old value from 'atomicrmw'.
2546 NewVVal = Res.second;
2547 } else {
2548 // 'atomicrmw' does not provide new value, so evaluate it using old
2549 // value of 'x'.
2550 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2551 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2552 NewVVal = CGF.EmitAnyExpr(UE);
2553 }
2554 }
2555 } else {
2556 // 'x' is simply rewritten with some 'expr'.
2557 NewVValType = X->getType().getNonReferenceType();
2558 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002559 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002560 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2561 NewVVal = XRValue;
2562 return ExprRValue;
2563 };
2564 // Try to perform atomicrmw xchg, otherwise simple exchange.
2565 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2566 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2567 Loc, Gen);
2568 if (Res.first) {
2569 // 'atomicrmw' instruction was generated.
2570 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2571 }
2572 }
2573 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002574 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002575 // OpenMP, 2.12.6, atomic Construct
2576 // Any atomic construct with a seq_cst clause forces the atomically
2577 // performed operation to include an implicit flush operation without a
2578 // list.
2579 if (IsSeqCst)
2580 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2581}
2582
Alexey Bataevb57056f2015-01-22 06:17:56 +00002583static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002584 bool IsSeqCst, bool IsPostfixUpdate,
2585 const Expr *X, const Expr *V, const Expr *E,
2586 const Expr *UE, bool IsXLHSInRHSPart,
2587 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002588 switch (Kind) {
2589 case OMPC_read:
2590 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2591 break;
2592 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002593 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2594 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002595 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002596 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002597 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2598 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002599 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002600 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2601 IsXLHSInRHSPart, Loc);
2602 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002603 case OMPC_if:
2604 case OMPC_final:
2605 case OMPC_num_threads:
2606 case OMPC_private:
2607 case OMPC_firstprivate:
2608 case OMPC_lastprivate:
2609 case OMPC_reduction:
2610 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002611 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002612 case OMPC_collapse:
2613 case OMPC_default:
2614 case OMPC_seq_cst:
2615 case OMPC_shared:
2616 case OMPC_linear:
2617 case OMPC_aligned:
2618 case OMPC_copyin:
2619 case OMPC_copyprivate:
2620 case OMPC_flush:
2621 case OMPC_proc_bind:
2622 case OMPC_schedule:
2623 case OMPC_ordered:
2624 case OMPC_nowait:
2625 case OMPC_untied:
2626 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002627 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002628 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002629 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002630 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002631 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002632 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002633 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002634 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002635 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002636 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002637 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002638 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002639 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002640 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002641 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002642 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2643 }
2644}
2645
2646void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002647 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002648 OpenMPClauseKind Kind = OMPC_unknown;
2649 for (auto *C : S.clauses()) {
2650 // Find first clause (skip seq_cst clause, if it is first).
2651 if (C->getClauseKind() != OMPC_seq_cst) {
2652 Kind = C->getClauseKind();
2653 break;
2654 }
2655 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002656
2657 const auto *CS =
2658 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002659 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002660 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002661 }
2662 // Processing for statements under 'atomic capture'.
2663 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2664 for (const auto *C : Compound->body()) {
2665 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2666 enterFullExpression(EWC);
2667 }
2668 }
2669 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002670
Alexey Bataev3392d762016-02-16 11:18:12 +00002671 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002672 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2673 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002674 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2675 S.getV(), S.getExpr(), S.getUpdateExpr(),
2676 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002677 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002678 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002679}
2680
Samuel Antaobed3c462015-10-02 16:14:20 +00002681void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002682 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002683 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2684
2685 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002686 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002687
Samuel Antaoee8fb302016-01-06 13:42:12 +00002688 llvm::Function *Fn = nullptr;
2689 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002690
2691 // Check if we have any if clause associated with the directive.
2692 const Expr *IfCond = nullptr;
2693
2694 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2695 IfCond = C->getCondition();
2696 }
2697
2698 // Check if we have any device clause associated with the directive.
2699 const Expr *Device = nullptr;
2700 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2701 Device = C->getDevice();
2702 }
2703
Samuel Antaoee8fb302016-01-06 13:42:12 +00002704 // Check if we have an if clause whose conditional always evaluates to false
2705 // or if we do not have any targets specified. If so the target region is not
2706 // an offload entry point.
2707 bool IsOffloadEntry = true;
2708 if (IfCond) {
2709 bool Val;
2710 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2711 IsOffloadEntry = false;
2712 }
2713 if (CGM.getLangOpts().OMPTargetTriples.empty())
2714 IsOffloadEntry = false;
2715
2716 assert(CurFuncDecl && "No parent declaration for target region!");
2717 StringRef ParentName;
2718 // In case we have Ctors/Dtors we use the complete type variant to produce
2719 // the mangling of the device outlined kernel.
2720 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2721 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2722 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2723 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2724 else
2725 ParentName =
2726 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2727
2728 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2729 IsOffloadEntry);
2730
2731 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002732 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002733}
2734
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002735static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
2736 const OMPExecutableDirective &S,
2737 OpenMPDirectiveKind InnermostKind,
2738 const RegionCodeGenTy &CodeGen) {
2739 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2740 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2741 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2742 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
2743 emitParallelOrTeamsOutlinedFunction(S,
2744 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00002745
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002746 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
2747 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
2748 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
2749 if (NT || TL) {
2750 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
2751 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
2752 /* isSigned = */ true) :
2753 CGF.Builder.getInt32(0);
2754
2755 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
2756 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
2757 /* isSigned = */ true) :
2758 CGF.Builder.getInt32(0);
2759
2760 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
2761 ThreadLimitVal, S.getLocStart());
2762 }
2763
2764 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
2765 CapturedVars);
2766}
2767
2768void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
2769 LexicalScope Scope(*this, S.getSourceRange());
2770 // Emit parallel region as a standalone region.
2771 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2772 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00002773 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
2774 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002775 (void)PrivateScope.Privatize();
2776 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2777 };
2778 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002779}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002780
2781void CodeGenFunction::EmitOMPCancellationPointDirective(
2782 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002783 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2784 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002785}
2786
Alexey Bataev80909872015-07-02 11:25:17 +00002787void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002788 const Expr *IfCond = nullptr;
2789 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2790 if (C->getNameModifier() == OMPD_unknown ||
2791 C->getNameModifier() == OMPD_cancel) {
2792 IfCond = C->getCondition();
2793 break;
2794 }
2795 }
2796 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002797 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002798}
2799
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002800CodeGenFunction::JumpDest
2801CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2802 if (Kind == OMPD_parallel || Kind == OMPD_task)
2803 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002804 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002805 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002806 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002807}
Michael Wong65f367f2015-07-21 13:44:28 +00002808
2809// Generate the instructions for '#pragma omp target data' directive.
2810void CodeGenFunction::EmitOMPTargetDataDirective(
2811 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002812 // emit the code inside the construct for now
2813 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002814 CGM.getOpenMPRuntime().emitInlinedDirective(
2815 *this, OMPD_target_data,
2816 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002817}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002818
Samuel Antaodf67fc42016-01-19 19:15:56 +00002819void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2820 const OMPTargetEnterDataDirective &S) {
2821 // TODO: codegen for target enter data.
2822}
2823
Samuel Antao72590762016-01-19 20:04:50 +00002824void CodeGenFunction::EmitOMPTargetExitDataDirective(
2825 const OMPTargetExitDataDirective &S) {
2826 // TODO: codegen for target exit data.
2827}
2828
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002829void CodeGenFunction::EmitOMPTargetParallelDirective(
2830 const OMPTargetParallelDirective &S) {
2831 // TODO: codegen for target parallel.
2832}
2833
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002834void CodeGenFunction::EmitOMPTargetParallelForDirective(
2835 const OMPTargetParallelForDirective &S) {
2836 // TODO: codegen for target parallel for.
2837}
2838
Alexey Bataev49f6e782015-12-01 04:18:41 +00002839void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2840 // emit the code inside the construct for now
2841 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2842 CGM.getOpenMPRuntime().emitInlinedDirective(
2843 *this, OMPD_taskloop,
2844 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2845}
2846
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002847void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2848 const OMPTaskLoopSimdDirective &S) {
2849 // emit the code inside the construct for now
2850 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2851 CGM.getOpenMPRuntime().emitInlinedDirective(
2852 *this, OMPD_taskloop_simd,
2853 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2854}
2855