blob: f911c71dcc06b6024ec931e41f07881fafc41e12 [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 Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Alexey Bataev4ba78a42016-04-27 07:56:03 +000029class OMPLexicalScope final : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 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 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 bool AsInlined = false)
58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +000060 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000061 if (AsInlined) {
62 if (S.hasAssociatedStmt()) {
63 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
64 for (auto &C : CS->captures()) {
65 if (C.capturesVariable() || C.capturesVariableByCopy()) {
66 auto *VD = C.getCapturedVar();
67 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
68 isCapturedVar(CGF, VD) ||
69 (CGF.CapturedStmtInfo &&
70 InlinedShareds.isGlobalVarCaptured(VD)),
71 VD->getType().getNonReferenceType(), VK_LValue,
72 SourceLocation());
73 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
74 return CGF.EmitLValue(&DRE).getAddress();
75 });
76 }
77 }
78 (void)InlinedShareds.Privatize();
79 }
80 }
Alexey Bataev3392d762016-02-16 11:18:12 +000081 }
82};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000083
Alexey Bataev5a3af132016-03-29 08:58:54 +000084/// Private scope for OpenMP loop-based directives, that supports capturing
85/// of used expression from loop statement.
86class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
87 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
88 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
89 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
90 for (const auto *I : PreInits->decls())
91 CGF.EmitVarDecl(cast<VarDecl>(*I));
92 }
93 }
94 }
95
96public:
97 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
98 : CodeGenFunction::RunCleanupsScope(CGF) {
99 emitPreInitStmt(CGF, S);
100 }
101};
102
Alexey Bataev3392d762016-02-16 11:18:12 +0000103} // namespace
104
Alexey Bataev1189bd02016-01-26 12:20:39 +0000105llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
106 auto &C = getContext();
107 llvm::Value *Size = nullptr;
108 auto SizeInChars = C.getTypeSizeInChars(Ty);
109 if (SizeInChars.isZero()) {
110 // getTypeSizeInChars() returns 0 for a VLA.
111 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
112 llvm::Value *ArraySize;
113 std::tie(ArraySize, Ty) = getVLASize(VAT);
114 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
115 }
116 SizeInChars = C.getTypeSizeInChars(Ty);
117 if (SizeInChars.isZero())
118 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
119 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
120 } else
121 Size = CGM.getSize(SizeInChars);
122 return Size;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 const RecordDecl *RD = S.getCapturedRecordDecl();
128 auto CurField = RD->field_begin();
129 auto CurCap = S.captures().begin();
130 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
131 E = S.capture_init_end();
132 I != E; ++I, ++CurField, ++CurCap) {
133 if (CurField->hasCapturedVLAType()) {
134 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000135 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000136 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000137 } else if (CurCap->capturesThis())
138 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000139 else if (CurCap->capturesVariableByCopy())
140 CapturedVars.push_back(
141 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
142 else {
143 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000144 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000145 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000146 }
147}
148
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000149static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
150 StringRef Name, LValue AddrLV,
151 bool isReferenceType = false) {
152 ASTContext &Ctx = CGF.getContext();
153
154 auto *CastedPtr = CGF.EmitScalarConversion(
155 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
156 Ctx.getPointerType(DstType), SourceLocation());
157 auto TmpAddr =
158 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
159 .getAddress();
160
161 // If we are dealing with references we need to return the address of the
162 // reference instead of the reference of the value.
163 if (isReferenceType) {
164 QualType RefType = Ctx.getLValueReferenceType(DstType);
165 auto *RefVal = TmpAddr.getPointer();
166 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
167 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
168 CGF.EmitScalarInit(RefVal, TmpLVal);
169 }
170
171 return TmpAddr;
172}
173
Alexey Bataev2377fe92015-09-10 08:12:02 +0000174llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000175CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000176 assert(
177 CapturedStmtInfo &&
178 "CapturedStmtInfo should be set when generating the captured function");
179 const CapturedDecl *CD = S.getCapturedDecl();
180 const RecordDecl *RD = S.getCapturedRecordDecl();
181 assert(CD->hasBody() && "missing CapturedDecl body");
182
183 // Build the argument list.
184 ASTContext &Ctx = CGM.getContext();
185 FunctionArgList Args;
186 Args.append(CD->param_begin(),
187 std::next(CD->param_begin(), CD->getContextParamPosition()));
188 auto I = S.captures().begin();
189 for (auto *FD : RD->fields()) {
190 QualType ArgType = FD->getType();
191 IdentifierInfo *II = nullptr;
192 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193
194 // If this is a capture by copy and the type is not a pointer, the outlined
195 // function argument type should be uintptr and the value properly casted to
196 // uintptr. This is necessary given that the runtime library is only able to
197 // deal with pointers. We can pass in the same way the VLA type sizes to the
198 // outlined function.
199 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
200 I->capturesVariableArrayType())
201 ArgType = Ctx.getUIntPtrType();
202
203 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000204 CapVar = I->getCapturedVar();
205 II = CapVar->getIdentifier();
206 } else if (I->capturesThis())
207 II = &getContext().Idents.get("this");
208 else {
209 assert(I->capturesVariableArrayType());
210 II = &getContext().Idents.get("vla");
211 }
212 if (ArgType->isVariablyModifiedType())
213 ArgType = getContext().getVariableArrayDecayedType(ArgType);
214 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
215 FD->getLocation(), II, ArgType));
216 ++I;
217 }
218 Args.append(
219 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
220 CD->param_end());
221
222 // Create the function declaration.
223 FunctionType::ExtInfo ExtInfo;
224 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000225 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000226 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
227
228 llvm::Function *F = llvm::Function::Create(
229 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
230 CapturedStmtInfo->getHelperName(), &CGM.getModule());
231 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
232 if (CD->isNothrow())
233 F->addFnAttr(llvm::Attribute::NoUnwind);
234
235 // Generate the function.
236 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
237 CD->getBody()->getLocStart());
238 unsigned Cnt = CD->getContextParamPosition();
239 I = S.captures().begin();
240 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000241 // If we are capturing a pointer by copy we don't need to do anything, just
242 // use the value that we get from the arguments.
243 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
244 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000245 ++Cnt;
246 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000247 continue;
248 }
249
Alexey Bataev2377fe92015-09-10 08:12:02 +0000250 LValue ArgLVal =
251 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
252 AlignmentSource::Decl);
253 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000254 LValue CastedArgLVal =
255 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
256 Args[Cnt]->getName(), ArgLVal),
257 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000258 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000259 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000260 auto VAT = FD->getCapturedVLAType();
261 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
262 } else if (I->capturesVariable()) {
263 auto *Var = I->getCapturedVar();
264 QualType VarTy = Var->getType();
265 Address ArgAddr = ArgLVal.getAddress();
266 if (!VarTy->isReferenceType()) {
267 ArgAddr = EmitLoadOfReference(
268 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
269 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000270 setAddrOfLocalVar(
271 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000272 } else if (I->capturesVariableByCopy()) {
273 assert(!FD->getType()->isAnyPointerType() &&
274 "Not expecting a captured pointer.");
275 auto *Var = I->getCapturedVar();
276 QualType VarTy = Var->getType();
277 setAddrOfLocalVar(I->getCapturedVar(),
278 castValueFromUintptr(*this, FD->getType(),
279 Args[Cnt]->getName(), ArgLVal,
280 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000281 } else {
282 // If 'this' is captured, load it into CXXThisValue.
283 assert(I->capturesThis());
284 CXXThisValue =
285 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
286 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000287 ++Cnt;
288 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000289 }
290
Serge Pavlov3a561452015-12-06 14:32:39 +0000291 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000292 CapturedStmtInfo->EmitBody(*this, CD->getBody());
293 FinishFunction(CD->getBodyRBrace());
294
295 return F;
296}
297
Alexey Bataev9959db52014-05-06 10:08:46 +0000298//===----------------------------------------------------------------------===//
299// OpenMP Directive Emission
300//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000302 Address DestAddr, Address SrcAddr, QualType OriginalType,
303 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000304 // Perform element-by-element initialization.
305 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000306
307 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000308 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000309 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
310 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
311
312 auto SrcBegin = SrcAddr.getPointer();
313 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000314 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000315 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
316 // The basic structure here is a while-do loop.
317 auto BodyBB = createBasicBlock("omp.arraycpy.body");
318 auto DoneBB = createBasicBlock("omp.arraycpy.done");
319 auto IsEmpty =
320 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
321 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000322
Alexey Bataev420d45b2015-04-14 05:11:24 +0000323 // Enter the loop body, making that address the current address.
324 auto EntryBB = Builder.GetInsertBlock();
325 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000326
327 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
328
329 llvm::PHINode *SrcElementPHI =
330 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
331 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
332 Address SrcElementCurrent =
333 Address(SrcElementPHI,
334 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
335
336 llvm::PHINode *DestElementPHI =
337 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
338 DestElementPHI->addIncoming(DestBegin, EntryBB);
339 Address DestElementCurrent =
340 Address(DestElementPHI,
341 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000342
Alexey Bataev420d45b2015-04-14 05:11:24 +0000343 // Emit copy.
344 CopyGen(DestElementCurrent, SrcElementCurrent);
345
346 // Shift the address forward by one element.
347 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000348 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000349 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000350 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000351 // Check whether we've reached the end.
352 auto Done =
353 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
354 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000355 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
356 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000357
358 // Done.
359 EmitBlock(DoneBB, /*IsFinished=*/true);
360}
361
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000362/// Check if the combiner is a call to UDR combiner and if it is so return the
363/// UDR decl used for reduction.
364static const OMPDeclareReductionDecl *
365getReductionInit(const Expr *ReductionOp) {
366 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
367 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
368 if (auto *DRE =
369 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
370 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
371 return DRD;
372 return nullptr;
373}
374
375static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
376 const OMPDeclareReductionDecl *DRD,
377 const Expr *InitOp,
378 Address Private, Address Original,
379 QualType Ty) {
380 if (DRD->getInitializer()) {
381 std::pair<llvm::Function *, llvm::Function *> Reduction =
382 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
383 auto *CE = cast<CallExpr>(InitOp);
384 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
385 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
386 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
387 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
388 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
389 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
390 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
391 [=]() -> Address { return Private; });
392 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
393 [=]() -> Address { return Original; });
394 (void)PrivateScope.Privatize();
395 RValue Func = RValue::get(Reduction.second);
396 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
397 CGF.EmitIgnoredExpr(InitOp);
398 } else {
399 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
400 auto *GV = new llvm::GlobalVariable(
401 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
402 llvm::GlobalValue::PrivateLinkage, Init, ".init");
403 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
404 RValue InitRVal;
405 switch (CGF.getEvaluationKind(Ty)) {
406 case TEK_Scalar:
407 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
408 break;
409 case TEK_Complex:
410 InitRVal =
411 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
412 break;
413 case TEK_Aggregate:
414 InitRVal = RValue::getAggregate(LV.getAddress());
415 break;
416 }
417 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
418 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
419 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
420 /*IsInitializer=*/false);
421 }
422}
423
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000424/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000425/// \param DestAddr Address of the array.
426/// \param Type Type of array.
427/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000428/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000429static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000430 QualType Type, const Expr *Init,
431 Address SrcAddr = Address::invalid()) {
432 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000433 // Perform element-by-element initialization.
434 QualType ElementTy;
435
436 // Drill down to the base element type on both arrays.
437 auto ArrayTy = Type->getAsArrayTypeUnsafe();
438 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
439 DestAddr =
440 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000441 if (DRD)
442 SrcAddr =
443 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000444
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000445 llvm::Value *SrcBegin = nullptr;
446 if (DRD)
447 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000448 auto DestBegin = DestAddr.getPointer();
449 // Cast from pointer to array type to pointer to single element.
450 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
451 // The basic structure here is a while-do loop.
452 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
453 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
454 auto IsEmpty =
455 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
456 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
457
458 // Enter the loop body, making that address the current address.
459 auto EntryBB = CGF.Builder.GetInsertBlock();
460 CGF.EmitBlock(BodyBB);
461
462 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
463
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000464 llvm::PHINode *SrcElementPHI = nullptr;
465 Address SrcElementCurrent = Address::invalid();
466 if (DRD) {
467 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
468 "omp.arraycpy.srcElementPast");
469 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
470 SrcElementCurrent =
471 Address(SrcElementPHI,
472 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
473 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000474 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
475 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
476 DestElementPHI->addIncoming(DestBegin, EntryBB);
477 Address DestElementCurrent =
478 Address(DestElementPHI,
479 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
480
481 // Emit copy.
482 {
483 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000484 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000485 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
486 SrcElementCurrent, ElementTy);
487 } else
488 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
489 /*IsInitializer=*/false);
490 }
491
492 if (DRD) {
493 // Shift the address forward by one element.
494 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
495 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
496 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000497 }
498
499 // Shift the address forward by one element.
500 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
501 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
502 // Check whether we've reached the end.
503 auto Done =
504 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
505 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
506 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
507
508 // Done.
509 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
510}
511
John McCall7f416cc2015-09-08 08:05:57 +0000512void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
513 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000514 const VarDecl *SrcVD, const Expr *Copy) {
515 if (OriginalType->isArrayType()) {
516 auto *BO = dyn_cast<BinaryOperator>(Copy);
517 if (BO && BO->getOpcode() == BO_Assign) {
518 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000519 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000520 } else {
521 // For arrays with complex element types perform element by element
522 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000523 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000524 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000525 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000526 // Working with the single array element, so have to remap
527 // destination and source variables to corresponding array
528 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000529 CodeGenFunction::OMPPrivateScope Remap(*this);
530 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000531 return DestElement;
532 });
533 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000534 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000535 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000536 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000537 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000538 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000539 } else {
540 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000541 CodeGenFunction::OMPPrivateScope Remap(*this);
542 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
543 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000544 (void)Remap.Privatize();
545 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000546 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000547 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000548}
549
Alexey Bataev69c62a92015-04-15 04:52:20 +0000550bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
551 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000552 if (!HaveInsertPoint())
553 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000554 bool FirstprivateIsLastprivate = false;
555 llvm::DenseSet<const VarDecl *> Lastprivates;
556 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
557 for (const auto *D : C->varlists())
558 Lastprivates.insert(
559 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
560 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000561 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000562 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000563 auto IRef = C->varlist_begin();
564 auto InitsRef = C->inits().begin();
565 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000566 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000567 FirstprivateIsLastprivate =
568 FirstprivateIsLastprivate ||
569 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
570 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000571 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
572 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
573 bool IsRegistered;
574 DeclRefExpr DRE(
575 const_cast<VarDecl *>(OrigVD),
576 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
577 OrigVD) != nullptr,
578 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000579 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000580 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000581 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000582 // Emit VarDecl with copy init for arrays.
583 // Get the address of the original variable captured in current
584 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000585 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000586 auto Emission = EmitAutoVarAlloca(*VD);
587 auto *Init = VD->getInit();
588 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
589 // Perform simple memcpy.
590 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000591 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000592 } else {
593 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000594 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000595 [this, VDInit, Init](Address DestElement,
596 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000597 // Clean up any temporaries needed by the initialization.
598 RunCleanupsScope InitScope(*this);
599 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000600 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000601 EmitAnyExprToMem(Init, DestElement,
602 Init->getType().getQualifiers(),
603 /*IsInitializer*/ false);
604 LocalDeclMap.erase(VDInit);
605 });
606 }
607 EmitAutoVarCleanups(Emission);
608 return Emission.getAllocatedAddress();
609 });
610 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000611 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000612 // Emit private VarDecl with copy init.
613 // Remap temp VDInit variable to the address of the original
614 // variable
615 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000616 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000617 EmitDecl(*VD);
618 LocalDeclMap.erase(VDInit);
619 return GetAddrOfLocalVar(VD);
620 });
621 }
622 assert(IsRegistered &&
623 "firstprivate var already registered as private");
624 // Silence the warning about unused variable.
625 (void)IsRegistered;
626 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000627 ++IRef;
628 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000629 }
630 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000631 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000632}
633
Alexey Bataev03b340a2014-10-21 03:16:40 +0000634void CodeGenFunction::EmitOMPPrivateClause(
635 const OMPExecutableDirective &D,
636 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000637 if (!HaveInsertPoint())
638 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000639 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000640 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000641 auto IRef = C->varlist_begin();
642 for (auto IInit : C->private_copies()) {
643 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000644 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
645 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
646 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000647 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000648 // Emit private VarDecl with copy init.
649 EmitDecl(*VD);
650 return GetAddrOfLocalVar(VD);
651 });
652 assert(IsRegistered && "private var already registered as private");
653 // Silence the warning about unused variable.
654 (void)IsRegistered;
655 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000656 ++IRef;
657 }
658 }
659}
660
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000661bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000662 if (!HaveInsertPoint())
663 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000664 // threadprivate_var1 = master_threadprivate_var1;
665 // operator=(threadprivate_var2, master_threadprivate_var2);
666 // ...
667 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000668 llvm::DenseSet<const VarDecl *> CopiedVars;
669 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000670 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000671 auto IRef = C->varlist_begin();
672 auto ISrcRef = C->source_exprs().begin();
673 auto IDestRef = C->destination_exprs().begin();
674 for (auto *AssignOp : C->assignment_ops()) {
675 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000676 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000677 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000678 // Get the address of the master variable. If we are emitting code with
679 // TLS support, the address is passed from the master as field in the
680 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000681 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000682 if (getLangOpts().OpenMPUseTLS &&
683 getContext().getTargetInfo().isTLSSupported()) {
684 assert(CapturedStmtInfo->lookup(VD) &&
685 "Copyin threadprivates should have been captured!");
686 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
687 VK_LValue, (*IRef)->getExprLoc());
688 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000689 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000690 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000691 MasterAddr =
692 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
693 : CGM.GetAddrOfGlobal(VD),
694 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000695 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000696 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000697 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000698 if (CopiedVars.size() == 1) {
699 // At first check if current thread is a master thread. If it is, no
700 // need to copy data.
701 CopyBegin = createBasicBlock("copyin.not.master");
702 CopyEnd = createBasicBlock("copyin.not.master.end");
703 Builder.CreateCondBr(
704 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000705 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
706 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000707 CopyBegin, CopyEnd);
708 EmitBlock(CopyBegin);
709 }
710 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
711 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000712 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000713 }
714 ++IRef;
715 ++ISrcRef;
716 ++IDestRef;
717 }
718 }
719 if (CopyEnd) {
720 // Exit out of copying procedure for non-master thread.
721 EmitBlock(CopyEnd, /*IsFinished=*/true);
722 return true;
723 }
724 return false;
725}
726
Alexey Bataev38e89532015-04-16 04:54:05 +0000727bool CodeGenFunction::EmitOMPLastprivateClauseInit(
728 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000729 if (!HaveInsertPoint())
730 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000731 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000732 llvm::DenseSet<const VarDecl *> SIMDLCVs;
733 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
734 auto *LoopDirective = cast<OMPLoopDirective>(&D);
735 for (auto *C : LoopDirective->counters()) {
736 SIMDLCVs.insert(
737 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
738 }
739 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000740 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000741 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000742 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000743 auto IRef = C->varlist_begin();
744 auto IDestRef = C->destination_exprs().begin();
745 for (auto *IInit : C->private_copies()) {
746 // Keep the address of the original variable for future update at the end
747 // of the loop.
748 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
749 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
750 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000751 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000752 DeclRefExpr DRE(
753 const_cast<VarDecl *>(OrigVD),
754 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
755 OrigVD) != nullptr,
756 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
757 return EmitLValue(&DRE).getAddress();
758 });
759 // Check if the variable is also a firstprivate: in this case IInit is
760 // not generated. Initialization of this variable will happen in codegen
761 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000762 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000763 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
764 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000765 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000766 // Emit private VarDecl with copy init.
767 EmitDecl(*VD);
768 return GetAddrOfLocalVar(VD);
769 });
770 assert(IsRegistered &&
771 "lastprivate var already registered as private");
772 (void)IsRegistered;
773 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000774 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000775 ++IRef;
776 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000777 }
778 }
779 return HasAtLeastOneLastprivate;
780}
781
782void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000783 const OMPExecutableDirective &D, bool NoFinals,
784 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000785 if (!HaveInsertPoint())
786 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000787 // Emit following code:
788 // if (<IsLastIterCond>) {
789 // orig_var1 = private_orig_var1;
790 // ...
791 // orig_varn = private_orig_varn;
792 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000793 llvm::BasicBlock *ThenBB = nullptr;
794 llvm::BasicBlock *DoneBB = nullptr;
795 if (IsLastIterCond) {
796 ThenBB = createBasicBlock(".omp.lastprivate.then");
797 DoneBB = createBasicBlock(".omp.lastprivate.done");
798 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
799 EmitBlock(ThenBB);
800 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000801 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
802 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000803 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000804 auto IC = LoopDirective->counters().begin();
805 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000806 auto *D =
807 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
808 if (NoFinals)
809 AlreadyEmittedVars.insert(D);
810 else
811 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000812 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000813 }
814 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000815 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
816 auto IRef = C->varlist_begin();
817 auto ISrcRef = C->source_exprs().begin();
818 auto IDestRef = C->destination_exprs().begin();
819 for (auto *AssignOp : C->assignment_ops()) {
820 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
821 QualType Type = PrivateVD->getType();
822 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
823 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
824 // If lastprivate variable is a loop control variable for loop-based
825 // directive, update its value before copyin back to original
826 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000827 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
828 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000829 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
830 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
831 // Get the address of the original variable.
832 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
833 // Get the address of the private variable.
834 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
835 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
836 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000837 Address(Builder.CreateLoad(PrivateAddr),
838 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000839 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000840 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000841 ++IRef;
842 ++ISrcRef;
843 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000844 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000845 if (auto *PostUpdate = C->getPostUpdateExpr())
846 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000847 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000848 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000849 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000850}
851
Alexey Bataev31300ed2016-02-04 11:27:03 +0000852static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
853 LValue BaseLV, llvm::Value *Addr) {
854 Address Tmp = Address::invalid();
855 Address TopTmp = Address::invalid();
856 Address MostTopTmp = Address::invalid();
857 BaseTy = BaseTy.getNonReferenceType();
858 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
859 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
860 Tmp = CGF.CreateMemTemp(BaseTy);
861 if (TopTmp.isValid())
862 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
863 else
864 MostTopTmp = Tmp;
865 TopTmp = Tmp;
866 BaseTy = BaseTy->getPointeeType();
867 }
868 llvm::Type *Ty = BaseLV.getPointer()->getType();
869 if (Tmp.isValid())
870 Ty = Tmp.getElementType();
871 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
872 if (Tmp.isValid()) {
873 CGF.Builder.CreateStore(Addr, Tmp);
874 return MostTopTmp;
875 }
876 return Address(Addr, BaseLV.getAlignment());
877}
878
879static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
880 LValue BaseLV) {
881 BaseTy = BaseTy.getNonReferenceType();
882 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
883 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
884 if (auto *PtrTy = BaseTy->getAs<PointerType>())
885 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
886 else {
887 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
888 BaseTy->castAs<ReferenceType>());
889 }
890 BaseTy = BaseTy->getPointeeType();
891 }
892 return CGF.MakeAddrLValue(
893 Address(
894 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
895 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
896 BaseLV.getAlignment()),
897 BaseLV.getType(), BaseLV.getAlignmentSource());
898}
899
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000900void CodeGenFunction::EmitOMPReductionClauseInit(
901 const OMPExecutableDirective &D,
902 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000903 if (!HaveInsertPoint())
904 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000905 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000906 auto ILHS = C->lhs_exprs().begin();
907 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000908 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000909 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000910 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000911 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000912 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
913 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000914 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000915 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
916 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
917 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
918 Base = TempOASE->getBase()->IgnoreParenImpCasts();
919 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
920 Base = TempASE->getBase()->IgnoreParenImpCasts();
921 auto *DE = cast<DeclRefExpr>(Base);
922 auto *OrigVD = cast<VarDecl>(DE->getDecl());
923 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
924 auto OASELValueUB =
925 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
926 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000927 LValue BaseLValue =
928 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
929 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 // Store the address of the original variable associated with the LHS
931 // implicit variable.
932 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
933 return OASELValueLB.getAddress();
934 });
935 // Emit reduction copy.
936 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000937 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000938 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000939 // Emit VarDecl with copy init for arrays.
940 // Get the address of the original variable captured in current
941 // captured region.
942 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
943 OASELValueLB.getPointer());
944 Size = Builder.CreateNUWAdd(
945 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
946 CodeGenFunction::OpaqueValueMapping OpaqueMap(
947 *this, cast<OpaqueValueExpr>(
948 getContext()
949 .getAsVariableArrayType(PrivateVD->getType())
950 ->getSizeExpr()),
951 RValue::get(Size));
952 EmitVariablyModifiedType(PrivateVD->getType());
953 auto Emission = EmitAutoVarAlloca(*PrivateVD);
954 auto Addr = Emission.getAllocatedAddress();
955 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000956 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
957 DRD ? *IRed : Init,
958 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000959 EmitAutoVarCleanups(Emission);
960 // Emit private VarDecl with reduction init.
961 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
962 OASELValueLB.getPointer());
963 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000964 return castToBase(*this, OrigVD->getType(),
965 OASELValueLB.getType(), OriginalBaseLValue,
966 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000967 });
968 assert(IsRegistered && "private var already registered as private");
969 // Silence the warning about unused variable.
970 (void)IsRegistered;
971 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
972 return GetAddrOfLocalVar(PrivateVD);
973 });
974 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
975 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
976 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
977 Base = TempASE->getBase()->IgnoreParenImpCasts();
978 auto *DE = cast<DeclRefExpr>(Base);
979 auto *OrigVD = cast<VarDecl>(DE->getDecl());
980 auto ASELValue = EmitLValue(ASE);
981 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000982 LValue BaseLValue = loadToBegin(
983 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000984 // Store the address of the original variable associated with the LHS
985 // implicit variable.
986 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
987 return ASELValue.getAddress();
988 });
989 // Emit reduction copy.
990 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000991 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000992 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000993 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000994 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
995 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000996 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000997 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
998 ASELValue.getAddress(),
999 ASELValue.getType());
1000 } else
1001 EmitAutoVarInit(Emission);
1002 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001003 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1004 ASELValue.getPointer());
1005 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001006 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1007 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001008 });
1009 assert(IsRegistered && "private var already registered as private");
1010 // Silence the warning about unused variable.
1011 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001012 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1013 return Builder.CreateElementBitCast(
1014 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1015 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001016 });
1017 } else {
1018 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001019 QualType Type = PrivateVD->getType();
1020 if (getContext().getAsArrayType(Type)) {
1021 // Store the address of the original variable associated with the LHS
1022 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001023 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1024 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1025 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001026 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001027 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001028 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001029 OriginalAddr = Builder.CreateElementBitCast(
1030 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1031 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001032 });
1033 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1034 if (Type->isVariablyModifiedType()) {
1035 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1036 *this, cast<OpaqueValueExpr>(
1037 getContext()
1038 .getAsVariableArrayType(PrivateVD->getType())
1039 ->getSizeExpr()),
1040 RValue::get(
1041 getTypeSize(OrigVD->getType().getNonReferenceType())));
1042 EmitVariablyModifiedType(Type);
1043 }
1044 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1045 auto Addr = Emission.getAllocatedAddress();
1046 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001047 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1048 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001049 EmitAutoVarCleanups(Emission);
1050 return Emission.getAllocatedAddress();
1051 });
1052 assert(IsRegistered && "private var already registered as private");
1053 // Silence the warning about unused variable.
1054 (void)IsRegistered;
1055 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1056 return Builder.CreateElementBitCast(
1057 GetAddrOfLocalVar(PrivateVD),
1058 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1059 });
1060 } else {
1061 // Store the address of the original variable associated with the LHS
1062 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001063 Address OriginalAddr = Address::invalid();
1064 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1065 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001066 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1067 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1068 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001069 OriginalAddr = EmitLValue(&DRE).getAddress();
1070 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001071 });
1072 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001073 bool IsRegistered = PrivateScope.addPrivate(
1074 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001075 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001076 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1077 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001078 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001079 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1080 OriginalAddr,
1081 PrivateVD->getType());
1082 } else
1083 EmitAutoVarInit(Emission);
1084 EmitAutoVarCleanups(Emission);
1085 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001086 });
1087 assert(IsRegistered && "private var already registered as private");
1088 // Silence the warning about unused variable.
1089 (void)IsRegistered;
1090 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1091 return GetAddrOfLocalVar(PrivateVD);
1092 });
1093 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001094 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001095 ++ILHS;
1096 ++IRHS;
1097 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001098 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001099 }
1100 }
1101}
1102
1103void CodeGenFunction::EmitOMPReductionClauseFinal(
1104 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001105 if (!HaveInsertPoint())
1106 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001107 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001108 llvm::SmallVector<const Expr *, 8> LHSExprs;
1109 llvm::SmallVector<const Expr *, 8> RHSExprs;
1110 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001111 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001112 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001113 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001114 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001115 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1116 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1117 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1118 }
1119 if (HasAtLeastOneReduction) {
1120 // Emit nowait reduction if nowait clause is present or directive is a
1121 // parallel directive (it always has implicit barrier).
1122 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001123 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001124 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001125 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1126 D.getDirectiveKind() == OMPD_simd,
1127 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001128 }
1129}
1130
Alexey Bataev61205072016-03-02 04:57:40 +00001131static void emitPostUpdateForReductionClause(
1132 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1133 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1134 if (!CGF.HaveInsertPoint())
1135 return;
1136 llvm::BasicBlock *DoneBB = nullptr;
1137 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1138 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1139 if (!DoneBB) {
1140 if (auto *Cond = CondGen(CGF)) {
1141 // If the first post-update expression is found, emit conditional
1142 // block if it was requested.
1143 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1144 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1145 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1146 CGF.EmitBlock(ThenBB);
1147 }
1148 }
1149 CGF.EmitIgnoredExpr(PostUpdate);
1150 }
1151 }
1152 if (DoneBB)
1153 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1154}
1155
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001156static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1157 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001158 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001159 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001160 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001161 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1162 emitParallelOrTeamsOutlinedFunction(S,
1163 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001164 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001165 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001166 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1167 /*IgnoreResultAssign*/ true);
1168 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1169 CGF, NumThreads, NumThreadsClause->getLocStart());
1170 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001171 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001172 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001173 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1174 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1175 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001176 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001177 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1178 if (C->getNameModifier() == OMPD_unknown ||
1179 C->getNameModifier() == OMPD_parallel) {
1180 IfCond = C->getCondition();
1181 break;
1182 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001183 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001184
1185 OMPLexicalScope Scope(CGF, S);
1186 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1187 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001188 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001189 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190}
1191
1192void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001193 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001194 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001195 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001196 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001197 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1198 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001199 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001200 // propagation master's thread values of threadprivate variables to local
1201 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001202 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1203 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1204 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001205 }
1206 CGF.EmitOMPPrivateClause(S, PrivateScope);
1207 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1208 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001209 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001210 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001211 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001212 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001213 emitPostUpdateForReductionClause(
1214 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001215}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001216
Alexey Bataev0f34da12015-07-02 04:17:07 +00001217void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1218 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001219 RunCleanupsScope BodyScope(*this);
1220 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001221 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001222 EmitIgnoredExpr(I);
1223 }
Alexander Musman3276a272015-03-21 10:12:56 +00001224 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001225 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001226 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001227 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001228 }
1229
Alexander Musmana5f070a2014-10-01 06:03:56 +00001230 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001231 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001232 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001233 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001234 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001235 // The end (updates/cleanups).
1236 EmitBlock(Continue.getBlock());
1237 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001238}
1239
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001240void CodeGenFunction::EmitOMPInnerLoop(
1241 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1242 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001243 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1244 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001245 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246
1247 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001248 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001249 EmitBlock(CondBlock);
1250 LoopStack.push(CondBlock);
1251
1252 // If there are any cleanups between here and the loop-exit scope,
1253 // create a block to stage a loop exit along.
1254 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001255 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001256 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001257
Alexander Musmand196ef22014-10-07 08:57:09 +00001258 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001259
Alexey Bataev2df54a02015-03-12 08:53:29 +00001260 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001261 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001262 if (ExitBlock != LoopExit.getBlock()) {
1263 EmitBlock(ExitBlock);
1264 EmitBranchThroughCleanup(LoopExit);
1265 }
1266
1267 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001268 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001269
1270 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001271 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001272 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1273
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001274 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275
1276 // Emit "IV = IV + 1" and a back-edge to the condition block.
1277 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001278 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001279 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001280 BreakContinueStack.pop_back();
1281 EmitBranch(CondBlock);
1282 LoopStack.pop();
1283 // Emit the fall-through block.
1284 EmitBlock(LoopExit.getBlock());
1285}
1286
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001287void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001288 if (!HaveInsertPoint())
1289 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001290 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001291 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001292 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001293 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001294 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1295 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1296 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1297 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1298 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1299 VD->getInit()->getType(), VK_LValue,
1300 VD->getInit()->getExprLoc());
1301 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1302 VD->getType()),
1303 /*capturedByInit=*/false);
1304 EmitAutoVarCleanups(Emission);
1305 } else
1306 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001307 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001308 // Emit the linear steps for the linear clauses.
1309 // If a step is not constant, it is pre-calculated before the loop.
1310 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1311 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001312 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001313 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001314 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001315 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001316 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001317}
1318
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001319void CodeGenFunction::EmitOMPLinearClauseFinal(
1320 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001321 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001322 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001323 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001324 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001325 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001326 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001327 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001329 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001330 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001331 // If the first post-update expression is found, emit conditional
1332 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001333 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1334 DoneBB = createBasicBlock(".omp.linear.pu.done");
1335 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1336 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001337 }
1338 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001339 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1340 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001342 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001343 Address OrigAddr = EmitLValue(&DRE).getAddress();
1344 CodeGenFunction::OMPPrivateScope VarScope(*this);
1345 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001346 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001347 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001348 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001349 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001350 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001351 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001352 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001353 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001354 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001355}
1356
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001357static void emitAlignedClause(CodeGenFunction &CGF,
1358 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001359 if (!CGF.HaveInsertPoint())
1360 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001361 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001362 unsigned ClauseAlignment = 0;
1363 if (auto AlignmentExpr = Clause->getAlignment()) {
1364 auto AlignmentCI =
1365 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1366 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001367 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 for (auto E : Clause->varlists()) {
1369 unsigned Alignment = ClauseAlignment;
1370 if (Alignment == 0) {
1371 // OpenMP [2.8.1, Description]
1372 // If no optional parameter is specified, implementation-defined default
1373 // alignments for SIMD instructions on the target platforms are assumed.
1374 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001375 CGF.getContext()
1376 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1377 E->getType()->getPointeeType()))
1378 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001379 }
1380 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1381 "alignment is not power of 2");
1382 if (Alignment != 0) {
1383 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1384 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1385 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001386 }
1387 }
1388}
1389
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001390void CodeGenFunction::EmitOMPPrivateLoopCounters(
1391 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1392 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001393 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001394 auto I = S.private_counters().begin();
1395 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001396 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1397 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001399 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400 if (!LocalDeclMap.count(PrivateVD)) {
1401 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1402 EmitAutoVarCleanups(VarEmission);
1403 }
1404 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1405 /*RefersToEnclosingVariableOrCapture=*/false,
1406 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1407 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001408 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1410 VD->hasGlobalStorage()) {
1411 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1412 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1413 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1414 E->getType(), VK_LValue, E->getExprLoc());
1415 return EmitLValue(&DRE).getAddress();
1416 });
1417 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001418 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001419 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001420}
1421
Alexey Bataev62dbb972015-04-22 11:59:37 +00001422static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1423 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1424 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001425 if (!CGF.HaveInsertPoint())
1426 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001427 {
1428 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001429 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001430 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001431 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001432 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001433 CGF.EmitIgnoredExpr(I);
1434 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001435 }
1436 // Check that loop is executed at least one time.
1437 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1438}
1439
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001440void CodeGenFunction::EmitOMPLinearClause(
1441 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1442 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001443 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001444 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1445 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1446 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1447 for (auto *C : LoopDirective->counters()) {
1448 SIMDLCVs.insert(
1449 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1450 }
1451 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001452 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001453 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001454 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001455 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1456 auto *PrivateVD =
1457 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001458 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1459 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1460 // Emit private VarDecl with copy init.
1461 EmitVarDecl(*PrivateVD);
1462 return GetAddrOfLocalVar(PrivateVD);
1463 });
1464 assert(IsRegistered && "linear var already registered as private");
1465 // Silence the warning about unused variable.
1466 (void)IsRegistered;
1467 } else
1468 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001469 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001470 }
1471 }
1472}
1473
Alexey Bataev45bfad52015-08-21 12:19:04 +00001474static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001475 const OMPExecutableDirective &D,
1476 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001477 if (!CGF.HaveInsertPoint())
1478 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001479 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001480 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1481 /*ignoreResult=*/true);
1482 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1483 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1484 // In presence of finite 'safelen', it may be unsafe to mark all
1485 // the memory instructions parallel, because loop-carried
1486 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001487 if (!IsMonotonic)
1488 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001489 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001490 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1491 /*ignoreResult=*/true);
1492 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001493 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001494 // In presence of finite 'safelen', it may be unsafe to mark all
1495 // the memory instructions parallel, because loop-carried
1496 // dependences of 'safelen' iterations are possible.
1497 CGF.LoopStack.setParallel(false);
1498 }
1499}
1500
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001501void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1502 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001503 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001504 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001505 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001506 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001507}
1508
Alexey Bataevef549a82016-03-09 09:49:09 +00001509void CodeGenFunction::EmitOMPSimdFinal(
1510 const OMPLoopDirective &D,
1511 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001512 if (!HaveInsertPoint())
1513 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001514 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001515 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001516 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001517 for (auto F : D.finals()) {
1518 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001519 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1520 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1521 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1522 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001523 if (!DoneBB) {
1524 if (auto *Cond = CondGen(*this)) {
1525 // If the first post-update expression is found, emit conditional
1526 // block if it was requested.
1527 auto *ThenBB = createBasicBlock(".omp.final.then");
1528 DoneBB = createBasicBlock(".omp.final.done");
1529 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1530 EmitBlock(ThenBB);
1531 }
1532 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001533 Address OrigAddr = Address::invalid();
1534 if (CED)
1535 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1536 else {
1537 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1538 /*RefersToEnclosingVariableOrCapture=*/false,
1539 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1540 OrigAddr = EmitLValue(&DRE).getAddress();
1541 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001542 OMPPrivateScope VarScope(*this);
1543 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001544 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001545 (void)VarScope.Privatize();
1546 EmitIgnoredExpr(F);
1547 }
1548 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001549 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001550 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001551 if (DoneBB)
1552 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001553}
1554
Alexander Musman515ad8c2014-05-22 08:54:05 +00001555void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001556 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001557 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001558 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001559 // for (IV in 0..LastIteration) BODY;
1560 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001561 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001562 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001563
Alexey Bataev62dbb972015-04-22 11:59:37 +00001564 // Emit: if (PreCond) - begin.
1565 // If the condition constant folds and can be elided, avoid emitting the
1566 // whole loop.
1567 bool CondConstant;
1568 llvm::BasicBlock *ContBlock = nullptr;
1569 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1570 if (!CondConstant)
1571 return;
1572 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001573 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1574 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001575 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1576 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001577 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001578 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001579 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001580
1581 // Emit the loop iteration variable.
1582 const Expr *IVExpr = S.getIterationVariable();
1583 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1584 CGF.EmitVarDecl(*IVDecl);
1585 CGF.EmitIgnoredExpr(S.getInit());
1586
1587 // Emit the iterations count variable.
1588 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001589 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001590 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1591 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1592 // Emit calculation of the iterations count.
1593 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001594 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001595
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001596 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001597
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001598 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001599 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001600 {
1601 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001602 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1603 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001604 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001605 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001606 bool HasLastprivateClause =
1607 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001608 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001609 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1610 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001611 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001612 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001613 CGF.EmitStopPoint(&S);
1614 },
1615 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001616 CGF.EmitOMPSimdFinal(
1617 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001618 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001619 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001620 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001621 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001622 emitPostUpdateForReductionClause(
1623 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001624 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001625 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001626 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001627 // Emit: if (PreCond) - end.
1628 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001629 CGF.EmitBranch(ContBlock);
1630 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001631 }
1632 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001633 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001634 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001635}
1636
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001637void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001638 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1639 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001640 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001641
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001642 const Expr *IVExpr = S.getIterationVariable();
1643 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1644 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1645
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001646 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1647
1648 // Start the loop with a block that tests the condition.
1649 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1650 EmitBlock(CondBlock);
1651 LoopStack.push(CondBlock);
1652
1653 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001654 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001655 // UB = min(UB, GlobalUB)
1656 EmitIgnoredExpr(S.getEnsureUpperBound());
1657 // IV = LB
1658 EmitIgnoredExpr(S.getInit());
1659 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001660 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001661 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001662 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1663 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001664 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001665
1666 // If there are any cleanups between here and the loop-exit scope,
1667 // create a block to stage a loop exit along.
1668 auto ExitBlock = LoopExit.getBlock();
1669 if (LoopScope.requiresCleanups())
1670 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1671
1672 auto LoopBody = createBasicBlock("omp.dispatch.body");
1673 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1674 if (ExitBlock != LoopExit.getBlock()) {
1675 EmitBlock(ExitBlock);
1676 EmitBranchThroughCleanup(LoopExit);
1677 }
1678 EmitBlock(LoopBody);
1679
Alexander Musman92bdaab2015-03-12 13:37:50 +00001680 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1681 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001682 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683 EmitIgnoredExpr(S.getInit());
1684
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001685 // Create a block for the increment.
1686 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1687 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1688
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001689 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1690 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001691 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1692 LoopStack.setParallel(!IsMonotonic);
1693 else
1694 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001695
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001696 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001697 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1698 [&S, LoopExit](CodeGenFunction &CGF) {
1699 CGF.EmitOMPLoopBody(S, LoopExit);
1700 CGF.EmitStopPoint(&S);
1701 },
1702 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1703 if (Ordered) {
1704 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1705 CGF, Loc, IVSize, IVSigned);
1706 }
1707 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001708
1709 EmitBlock(Continue.getBlock());
1710 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001711 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001712 // Emit "LB = LB + Stride", "UB = UB + Stride".
1713 EmitIgnoredExpr(S.getNextLowerBound());
1714 EmitIgnoredExpr(S.getNextUpperBound());
1715 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001716
1717 EmitBranch(CondBlock);
1718 LoopStack.pop();
1719 // Emit the fall-through block.
1720 EmitBlock(LoopExit.getBlock());
1721
1722 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001723 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001724 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001725
1726}
1727
1728void CodeGenFunction::EmitOMPForOuterLoop(
1729 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1730 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1731 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1732 auto &RT = CGM.getOpenMPRuntime();
1733
1734 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1735 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1736
1737 assert((Ordered ||
1738 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1739 "static non-chunked schedule does not need outer loop");
1740
1741 // Emit outer loop.
1742 //
1743 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1744 // When schedule(dynamic,chunk_size) is specified, the iterations are
1745 // distributed to threads in the team in chunks as the threads request them.
1746 // Each thread executes a chunk of iterations, then requests another chunk,
1747 // until no chunks remain to be distributed. Each chunk contains chunk_size
1748 // iterations, except for the last chunk to be distributed, which may have
1749 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1750 //
1751 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1752 // to threads in the team in chunks as the executing threads request them.
1753 // Each thread executes a chunk of iterations, then requests another chunk,
1754 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1755 // each chunk is proportional to the number of unassigned iterations divided
1756 // by the number of threads in the team, decreasing to 1. For a chunk_size
1757 // with value k (greater than 1), the size of each chunk is determined in the
1758 // same way, with the restriction that the chunks do not contain fewer than k
1759 // iterations (except for the last chunk to be assigned, which may have fewer
1760 // than k iterations).
1761 //
1762 // When schedule(auto) is specified, the decision regarding scheduling is
1763 // delegated to the compiler and/or runtime system. The programmer gives the
1764 // implementation the freedom to choose any possible mapping of iterations to
1765 // threads in the team.
1766 //
1767 // When schedule(runtime) is specified, the decision regarding scheduling is
1768 // deferred until run time, and the schedule and chunk size are taken from the
1769 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1770 // implementation defined
1771 //
1772 // while(__kmpc_dispatch_next(&LB, &UB)) {
1773 // idx = LB;
1774 // while (idx <= UB) { BODY; ++idx;
1775 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1776 // } // inner loop
1777 // }
1778 //
1779 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1780 // When schedule(static, chunk_size) is specified, iterations are divided into
1781 // chunks of size chunk_size, and the chunks are assigned to the threads in
1782 // the team in a round-robin fashion in the order of the thread number.
1783 //
1784 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1785 // while (idx <= UB) { BODY; ++idx; } // inner loop
1786 // LB = LB + ST;
1787 // UB = UB + ST;
1788 // }
1789 //
1790
1791 const Expr *IVExpr = S.getIterationVariable();
1792 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1793 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1794
1795 if (DynamicOrOrdered) {
1796 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1797 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1798 IVSize, IVSigned, Ordered, UBVal, Chunk);
1799 } else {
1800 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1801 Ordered, IL, LB, UB, ST, Chunk);
1802 }
1803
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001804 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001805 ST, IL, Chunk);
1806}
1807
1808void CodeGenFunction::EmitOMPDistributeOuterLoop(
1809 OpenMPDistScheduleClauseKind ScheduleKind,
1810 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1811 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1812
1813 auto &RT = CGM.getOpenMPRuntime();
1814
1815 // Emit outer loop.
1816 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1817 // dynamic
1818 //
1819
1820 const Expr *IVExpr = S.getIterationVariable();
1821 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1822 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1823
1824 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1825 IVSize, IVSigned, /* Ordered = */ false,
1826 IL, LB, UB, ST, Chunk);
1827
1828 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1829 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001830}
1831
Alexander Musmanc6388682014-12-15 07:07:06 +00001832/// \brief Emit a helper variable and return corresponding lvalue.
1833static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1834 const DeclRefExpr *Helper) {
1835 auto VDecl = cast<VarDecl>(Helper->getDecl());
1836 CGF.EmitVarDecl(*VDecl);
1837 return CGF.EmitLValue(Helper);
1838}
1839
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001840namespace {
1841 struct ScheduleKindModifiersTy {
1842 OpenMPScheduleClauseKind Kind;
1843 OpenMPScheduleClauseModifier M1;
1844 OpenMPScheduleClauseModifier M2;
1845 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1846 OpenMPScheduleClauseModifier M1,
1847 OpenMPScheduleClauseModifier M2)
1848 : Kind(Kind), M1(M1), M2(M2) {}
1849 };
1850} // namespace
1851
Alexey Bataev38e89532015-04-16 04:54:05 +00001852bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001853 // Emit the loop iteration variable.
1854 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1855 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1856 EmitVarDecl(*IVDecl);
1857
1858 // Emit the iterations count variable.
1859 // If it is not a variable, Sema decided to calculate iterations count on each
1860 // iteration (e.g., it is foldable into a constant).
1861 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1862 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1863 // Emit calculation of the iterations count.
1864 EmitIgnoredExpr(S.getCalcLastIteration());
1865 }
1866
1867 auto &RT = CGM.getOpenMPRuntime();
1868
Alexey Bataev38e89532015-04-16 04:54:05 +00001869 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001870 // Check pre-condition.
1871 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001872 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001873 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001874 // If the condition constant folds and can be elided, avoid emitting the
1875 // whole loop.
1876 bool CondConstant;
1877 llvm::BasicBlock *ContBlock = nullptr;
1878 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1879 if (!CondConstant)
1880 return false;
1881 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001882 auto *ThenBlock = createBasicBlock("omp.precond.then");
1883 ContBlock = createBasicBlock("omp.precond.end");
1884 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001885 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001886 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001887 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001888 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001889
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001890 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001891 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001892 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001893 // Emit helper vars inits.
1894 LValue LB =
1895 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1896 LValue UB =
1897 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1898 LValue ST =
1899 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1900 LValue IL =
1901 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1902
Alexander Musmanc6388682014-12-15 07:07:06 +00001903 // Emit 'then' code.
1904 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001905 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001906 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1907 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001908 // initialization of firstprivate variables and post-update of
1909 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001910 CGM.getOpenMPRuntime().emitBarrierCall(
1911 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1912 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001913 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001914 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001915 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001916 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001917 EmitOMPPrivateLoopCounters(S, LoopScope);
1918 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001919 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001920
1921 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001922 llvm::Value *Chunk = nullptr;
1923 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1924 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1925 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1926 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1927 ScheduleKind = C->getScheduleKind();
1928 M1 = C->getFirstScheduleModifier();
1929 M2 = C->getSecondScheduleModifier();
1930 if (const auto *Ch = C->getChunkSize()) {
1931 Chunk = EmitScalarExpr(Ch);
1932 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1933 S.getIterationVariable()->getType(),
1934 S.getLocStart());
1935 }
1936 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001937 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1938 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001939 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001940 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1941 // If the static schedule kind is specified or if the ordered clause is
1942 // specified, and if no monotonic modifier is specified, the effect will
1943 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001944 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001945 /* Chunked */ Chunk != nullptr) &&
1946 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001947 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1948 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001949 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1950 // When no chunk_size is specified, the iteration space is divided into
1951 // chunks that are approximately equal in size, and at most one chunk is
1952 // distributed to each thread. Note that the size of the chunks is
1953 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001954 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1955 IVSize, IVSigned, Ordered,
1956 IL.getAddress(), LB.getAddress(),
1957 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001958 auto LoopExit =
1959 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001960 // UB = min(UB, GlobalUB);
1961 EmitIgnoredExpr(S.getEnsureUpperBound());
1962 // IV = LB;
1963 EmitIgnoredExpr(S.getInit());
1964 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001965 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1966 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001967 [&S, LoopExit](CodeGenFunction &CGF) {
1968 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001969 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001970 },
1971 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001972 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001973 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001974 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001975 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001976 const bool IsMonotonic = Ordered ||
1977 ScheduleKind == OMPC_SCHEDULE_static ||
1978 ScheduleKind == OMPC_SCHEDULE_unknown ||
1979 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1980 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001981 // Emit the outer loop, which requests its work chunk [LB..UB] from
1982 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001983 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001984 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1985 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001986 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001987 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1988 EmitOMPSimdFinal(S,
1989 [&](CodeGenFunction &CGF) -> llvm::Value * {
1990 return CGF.Builder.CreateIsNotNull(
1991 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1992 });
1993 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001994 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001995 // Emit post-update of the reduction variables if IsLastIter != 0.
1996 emitPostUpdateForReductionClause(
1997 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1998 return CGF.Builder.CreateIsNotNull(
1999 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2000 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002001 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2002 if (HasLastprivateClause)
2003 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002004 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2005 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002006 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002007 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002008 return CGF.Builder.CreateIsNotNull(
2009 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2010 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002011 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002012 if (ContBlock) {
2013 EmitBranch(ContBlock);
2014 EmitBlock(ContBlock, true);
2015 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002016 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002017 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002018}
2019
2020void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002021 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002022 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2023 PrePostActionTy &) {
2024 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2025 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002026 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002027 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002028 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2029 S.hasCancel());
2030 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002031
2032 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002033 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002034 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2035 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002036}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002037
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002038void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002039 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002040 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2041 PrePostActionTy &) {
2042 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2043 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002044 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002045 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002046 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2047 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002048
2049 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002050 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002051 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2052 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002053}
2054
Alexey Bataev2df54a02015-03-12 08:53:29 +00002055static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2056 const Twine &Name,
2057 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002058 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002059 if (Init)
2060 CGF.EmitScalarInit(Init, LVal);
2061 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002062}
2063
Alexey Bataev3392d762016-02-16 11:18:12 +00002064void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002065 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2066 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002067 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002068 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2069 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002070 auto &C = CGF.CGM.getContext();
2071 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2072 // Emit helper vars inits.
2073 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2074 CGF.Builder.getInt32(0));
2075 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2076 : CGF.Builder.getInt32(0);
2077 LValue UB =
2078 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2079 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2080 CGF.Builder.getInt32(1));
2081 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2082 CGF.Builder.getInt32(0));
2083 // Loop counter.
2084 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2085 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2086 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2087 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2088 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2089 // Generate condition for loop.
2090 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2091 OK_Ordinary, S.getLocStart(),
2092 /*fpContractable=*/false);
2093 // Increment for loop counter.
2094 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2095 S.getLocStart());
2096 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2097 // Iterate through all sections and emit a switch construct:
2098 // switch (IV) {
2099 // case 0:
2100 // <SectionStmt[0]>;
2101 // break;
2102 // ...
2103 // case <NumSection> - 1:
2104 // <SectionStmt[<NumSection> - 1]>;
2105 // break;
2106 // }
2107 // .omp.sections.exit:
2108 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2109 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2110 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2111 CS == nullptr ? 1 : CS->size());
2112 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002113 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002114 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002115 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2116 CGF.EmitBlock(CaseBB);
2117 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002118 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002119 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002120 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002121 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002122 } else {
2123 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2124 CGF.EmitBlock(CaseBB);
2125 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2126 CGF.EmitStmt(Stmt);
2127 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002128 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002129 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002130 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002131
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002132 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2133 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002134 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002135 // initialization of firstprivate variables and post-update of lastprivate
2136 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002137 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2138 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2139 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002140 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002141 CGF.EmitOMPPrivateClause(S, LoopScope);
2142 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2143 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2144 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002145
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002146 // Emit static non-chunked loop.
2147 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2148 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
2149 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2150 UB.getAddress(), ST.getAddress());
2151 // UB = min(UB, GlobalUB);
2152 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2153 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2154 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2155 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2156 // IV = LB;
2157 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2158 // while (idx <= UB) { BODY; ++idx; }
2159 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2160 [](CodeGenFunction &) {});
2161 // Tell the runtime we are done.
2162 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2163 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002164 // Emit post-update of the reduction variables if IsLastIter != 0.
2165 emitPostUpdateForReductionClause(
2166 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2167 return CGF.Builder.CreateIsNotNull(
2168 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2169 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002170
2171 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2172 if (HasLastprivates)
2173 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002174 S, /*NoFinals=*/false,
2175 CGF.Builder.CreateIsNotNull(
2176 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002177 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002178
2179 bool HasCancel = false;
2180 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2181 HasCancel = OSD->hasCancel();
2182 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2183 HasCancel = OPSD->hasCancel();
2184 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2185 HasCancel);
2186 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2187 // clause. Otherwise the barrier will be generated by the codegen for the
2188 // directive.
2189 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002190 // Emit implicit barrier to synchronize threads and avoid data races on
2191 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002192 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2193 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002194 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002195}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002196
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002197void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002198 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002199 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002200 EmitSections(S);
2201 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002202 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002203 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002204 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2205 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002206 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002207}
2208
2209void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002210 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002211 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002212 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002213 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002214 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2215 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002216}
2217
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002218void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002219 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002220 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002221 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002222 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002223 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002224 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002225 // Build a list of copyprivate variables along with helper expressions
2226 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002227 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002228 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002229 DestExprs.append(C->destination_exprs().begin(),
2230 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002231 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002232 AssignmentOps.append(C->assignment_ops().begin(),
2233 C->assignment_ops().end());
2234 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002235 // Emit code for 'single' region along with 'copyprivate' clauses
2236 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2237 Action.Enter(CGF);
2238 OMPPrivateScope SingleScope(CGF);
2239 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2240 CGF.EmitOMPPrivateClause(S, SingleScope);
2241 (void)SingleScope.Privatize();
2242 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2243 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002244 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002245 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002246 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2247 CopyprivateVars, DestExprs,
2248 SrcExprs, AssignmentOps);
2249 }
2250 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2251 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002252 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002253 CGM.getOpenMPRuntime().emitBarrierCall(
2254 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002255 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002256 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002257}
2258
Alexey Bataev8d690652014-12-04 07:23:53 +00002259void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002260 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2261 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002262 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002263 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002264 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002265 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002266}
2267
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002268void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002269 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2270 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002271 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002272 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002273 Expr *Hint = nullptr;
2274 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2275 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002276 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002277 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2278 S.getDirectiveName().getAsString(),
2279 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002280}
2281
Alexey Bataev671605e2015-04-13 05:28:11 +00002282void CodeGenFunction::EmitOMPParallelForDirective(
2283 const OMPParallelForDirective &S) {
2284 // Emit directive as a combined directive that consists of two implicit
2285 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002286 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002287 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002288 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002289 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002290}
2291
Alexander Musmane4e893b2014-09-23 09:33:00 +00002292void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002293 const OMPParallelForSimdDirective &S) {
2294 // Emit directive as a combined directive that consists of two implicit
2295 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002296 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002297 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002298 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002299 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002300}
2301
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002302void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002303 const OMPParallelSectionsDirective &S) {
2304 // Emit directive as a combined directive that consists of two implicit
2305 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002306 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2307 CGF.EmitSections(S);
2308 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002309 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002310}
2311
Alexey Bataev7292c292016-04-25 12:22:29 +00002312void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2313 const RegionCodeGenTy &BodyGen,
2314 const TaskGenTy &TaskGen,
2315 bool Tied) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002316 // Emit outlined function for task construct.
2317 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002318 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002319 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002320 auto *TaskT = std::next(I, 4);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002321 // The first function argument for tasks is a thread id, the second one is a
2322 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002323 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2324 // Get list of private variables.
Alexey Bataev7292c292016-04-25 12:22:29 +00002325 OMPPrivateDataTy Data;
2326 Data.Tied = Tied;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002327 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002328 auto IRef = C->varlist_begin();
2329 for (auto *IInit : C->private_copies()) {
2330 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2331 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002332 Data.PrivateVars.push_back(*IRef);
2333 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002334 }
2335 ++IRef;
2336 }
2337 }
2338 EmittedAsPrivate.clear();
2339 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002340 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002341 auto IRef = C->varlist_begin();
2342 auto IElemInitRef = C->inits().begin();
2343 for (auto *IInit : C->private_copies()) {
2344 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2345 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002346 Data.FirstprivateVars.push_back(*IRef);
2347 Data.FirstprivateCopies.push_back(IInit);
2348 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002349 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002350 ++IRef;
2351 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002352 }
2353 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002354 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002355 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2356 for (auto *IRef : C->varlists())
2357 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2358 auto &&CodeGen = [PartId, &S, &Data, CS, &BodyGen](CodeGenFunction &CGF,
2359 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002360 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002361 OMPPrivateScope Scope(CGF);
2362 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002363 auto *CopyFn = CGF.Builder.CreateLoad(
2364 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2365 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2366 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2367 // Map privates.
2368 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2369 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2370 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002371 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002372 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2373 Address PrivatePtr = CGF.CreateMemTemp(
2374 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2375 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2376 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002377 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002378 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002379 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2380 Address PrivatePtr =
2381 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2382 ".firstpriv.ptr.addr");
2383 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2384 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002385 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002386 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2387 for (auto &&Pair : PrivatePtrs) {
2388 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2389 CGF.getContext().getDeclAlign(Pair.first));
2390 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2391 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002392 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002393 (void)Scope.Privatize();
2394
2395 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002396 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002397 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002398 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2399 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2400 Data.NumberOfParts);
2401 OMPLexicalScope Scope(*this, S);
2402 TaskGen(*this, OutlinedFn, Data);
2403}
2404
2405void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2406 // Emit outlined function for task construct.
2407 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2408 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002409 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002410 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002411 // Check if the task is final
2412 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002413 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002414 // If the condition constant folds and can be elided, try to avoid emitting
2415 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002416 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002417 bool CondConstant;
2418 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2419 Final.setInt(CondConstant);
2420 else
2421 Final.setPointer(EvaluateExprAsBool(Cond));
2422 } else {
2423 // By default the task is not final.
2424 Final.setInt(/*IntVal=*/false);
2425 }
2426 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002427 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002428 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2429 if (C->getNameModifier() == OMPD_unknown ||
2430 C->getNameModifier() == OMPD_task) {
2431 IfCond = C->getCondition();
2432 break;
2433 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002434 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002435
2436 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2437 CGF.EmitStmt(CS->getCapturedStmt());
2438 };
2439 auto &&TaskGen = [&S, &Final, SharedsTy, CapturedStruct,
2440 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
2441 const OMPPrivateDataTy &Data) {
2442 CGF.CGM.getOpenMPRuntime().emitTaskCall(
2443 CGF, S.getLocStart(), S, Data.Tied, Final, Data.NumberOfParts,
2444 OutlinedFn, SharedsTy, CapturedStruct, IfCond, Data.PrivateVars,
2445 Data.PrivateCopies, Data.FirstprivateVars, Data.FirstprivateCopies,
2446 Data.FirstprivateInits, Data.Dependences);
2447 };
2448 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Tied);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002449}
2450
Alexey Bataev9f797f32015-02-05 05:57:51 +00002451void CodeGenFunction::EmitOMPTaskyieldDirective(
2452 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002453 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002454}
2455
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002456void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002457 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002458}
2459
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002460void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2461 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002462}
2463
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002464void CodeGenFunction::EmitOMPTaskgroupDirective(
2465 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002466 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2467 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002468 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002469 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002470 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002471 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2472}
2473
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002474void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002475 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002476 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002477 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2478 FlushClause->varlist_end());
2479 }
2480 return llvm::None;
2481 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002482}
2483
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002484void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2485 // Emit the loop iteration variable.
2486 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2487 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2488 EmitVarDecl(*IVDecl);
2489
2490 // Emit the iterations count variable.
2491 // If it is not a variable, Sema decided to calculate iterations count on each
2492 // iteration (e.g., it is foldable into a constant).
2493 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2494 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2495 // Emit calculation of the iterations count.
2496 EmitIgnoredExpr(S.getCalcLastIteration());
2497 }
2498
2499 auto &RT = CGM.getOpenMPRuntime();
2500
2501 // Check pre-condition.
2502 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002503 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002504 // Skip the entire loop if we don't meet the precondition.
2505 // If the condition constant folds and can be elided, avoid emitting the
2506 // whole loop.
2507 bool CondConstant;
2508 llvm::BasicBlock *ContBlock = nullptr;
2509 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2510 if (!CondConstant)
2511 return;
2512 } else {
2513 auto *ThenBlock = createBasicBlock("omp.precond.then");
2514 ContBlock = createBasicBlock("omp.precond.end");
2515 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2516 getProfileCount(&S));
2517 EmitBlock(ThenBlock);
2518 incrementProfileCounter(&S);
2519 }
2520
2521 // Emit 'then' code.
2522 {
2523 // Emit helper vars inits.
2524 LValue LB =
2525 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2526 LValue UB =
2527 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2528 LValue ST =
2529 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2530 LValue IL =
2531 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2532
2533 OMPPrivateScope LoopScope(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002534 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002535 (void)LoopScope.Privatize();
2536
2537 // Detect the distribute schedule kind and chunk.
2538 llvm::Value *Chunk = nullptr;
2539 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2540 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2541 ScheduleKind = C->getDistScheduleKind();
2542 if (const auto *Ch = C->getChunkSize()) {
2543 Chunk = EmitScalarExpr(Ch);
2544 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2545 S.getIterationVariable()->getType(),
2546 S.getLocStart());
2547 }
2548 }
2549 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2550 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2551
2552 // OpenMP [2.10.8, distribute Construct, Description]
2553 // If dist_schedule is specified, kind must be static. If specified,
2554 // iterations are divided into chunks of size chunk_size, chunks are
2555 // assigned to the teams of the league in a round-robin fashion in the
2556 // order of the team number. When no chunk_size is specified, the
2557 // iteration space is divided into chunks that are approximately equal
2558 // in size, and at most one chunk is distributed to each team of the
2559 // league. The size of the chunks is unspecified in this case.
2560 if (RT.isStaticNonchunked(ScheduleKind,
2561 /* Chunked */ Chunk != nullptr)) {
2562 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2563 IVSize, IVSigned, /* Ordered = */ false,
2564 IL.getAddress(), LB.getAddress(),
2565 UB.getAddress(), ST.getAddress());
2566 auto LoopExit =
2567 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2568 // UB = min(UB, GlobalUB);
2569 EmitIgnoredExpr(S.getEnsureUpperBound());
2570 // IV = LB;
2571 EmitIgnoredExpr(S.getInit());
2572 // while (idx <= UB) { BODY; ++idx; }
2573 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2574 S.getInc(),
2575 [&S, LoopExit](CodeGenFunction &CGF) {
2576 CGF.EmitOMPLoopBody(S, LoopExit);
2577 CGF.EmitStopPoint(&S);
2578 },
2579 [](CodeGenFunction &) {});
2580 EmitBlock(LoopExit.getBlock());
2581 // Tell the runtime we are done.
2582 RT.emitForStaticFinish(*this, S.getLocStart());
2583 } else {
2584 // Emit the outer loop, which requests its work chunk [LB..UB] from
2585 // runtime and runs the inner loop to process it.
2586 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2587 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2588 IL.getAddress(), Chunk);
2589 }
2590 }
2591
2592 // We're now done with the loop, so jump to the continuation block.
2593 if (ContBlock) {
2594 EmitBranch(ContBlock);
2595 EmitBlock(ContBlock, true);
2596 }
2597 }
2598}
2599
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002600void CodeGenFunction::EmitOMPDistributeDirective(
2601 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002603 CGF.EmitOMPDistributeLoop(S);
2604 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002605 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002606 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2607 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002608}
2609
Alexey Bataev5f600d62015-09-29 03:48:57 +00002610static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2611 const CapturedStmt *S) {
2612 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2613 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2614 CGF.CapturedStmtInfo = &CapStmtInfo;
2615 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2616 Fn->addFnAttr(llvm::Attribute::NoInline);
2617 return Fn;
2618}
2619
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002620void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002621 if (!S.getAssociatedStmt())
2622 return;
Alexey Bataev5f600d62015-09-29 03:48:57 +00002623 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002624 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2625 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002626 if (C) {
2627 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2628 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2629 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2630 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2631 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2632 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002633 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002634 CGF.EmitStmt(
2635 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2636 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002637 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002638 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002639 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002640}
2641
Alexey Bataevb57056f2015-01-22 06:17:56 +00002642static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002643 QualType SrcType, QualType DestType,
2644 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002645 assert(CGF.hasScalarEvaluationKind(DestType) &&
2646 "DestType must have scalar evaluation kind.");
2647 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2648 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002649 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2650 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002651 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002652 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002653}
2654
2655static CodeGenFunction::ComplexPairTy
2656convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002657 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002658 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2659 "DestType must have complex evaluation kind.");
2660 CodeGenFunction::ComplexPairTy ComplexVal;
2661 if (Val.isScalar()) {
2662 // Convert the input element to the element type of the complex.
2663 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002664 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2665 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002666 ComplexVal = CodeGenFunction::ComplexPairTy(
2667 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2668 } else {
2669 assert(Val.isComplex() && "Must be a scalar or complex.");
2670 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2671 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2672 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002673 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002674 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002675 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002676 }
2677 return ComplexVal;
2678}
2679
Alexey Bataev5e018f92015-04-23 06:35:10 +00002680static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2681 LValue LVal, RValue RVal) {
2682 if (LVal.isGlobalReg()) {
2683 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2684 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002685 CGF.EmitAtomicStore(RVal, LVal,
2686 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2687 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002688 LVal.isVolatile(), /*IsInit=*/false);
2689 }
2690}
2691
Alexey Bataev8524d152016-01-21 12:35:58 +00002692void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2693 QualType RValTy, SourceLocation Loc) {
2694 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002695 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002696 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2697 *this, RVal, RValTy, LVal.getType(), Loc)),
2698 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002699 break;
2700 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002701 EmitStoreOfComplex(
2702 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002703 /*isInit=*/false);
2704 break;
2705 case TEK_Aggregate:
2706 llvm_unreachable("Must be a scalar or complex.");
2707 }
2708}
2709
Alexey Bataevb57056f2015-01-22 06:17:56 +00002710static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2711 const Expr *X, const Expr *V,
2712 SourceLocation Loc) {
2713 // v = x;
2714 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2715 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2716 LValue XLValue = CGF.EmitLValue(X);
2717 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002718 RValue Res = XLValue.isGlobalReg()
2719 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00002720 : CGF.EmitAtomicLoad(
2721 XLValue, Loc,
2722 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2723 : llvm::AtomicOrdering::Monotonic,
2724 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002725 // OpenMP, 2.12.6, atomic Construct
2726 // Any atomic construct with a seq_cst clause forces the atomically
2727 // performed operation to include an implicit flush operation without a
2728 // list.
2729 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002730 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002731 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002732}
2733
Alexey Bataevb8329262015-02-27 06:33:30 +00002734static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2735 const Expr *X, const Expr *E,
2736 SourceLocation Loc) {
2737 // x = expr;
2738 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002739 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002740 // OpenMP, 2.12.6, atomic Construct
2741 // Any atomic construct with a seq_cst clause forces the atomically
2742 // performed operation to include an implicit flush operation without a
2743 // list.
2744 if (IsSeqCst)
2745 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2746}
2747
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002748static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2749 RValue Update,
2750 BinaryOperatorKind BO,
2751 llvm::AtomicOrdering AO,
2752 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002753 auto &Context = CGF.CGM.getContext();
2754 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002755 // expression is simple and atomic is allowed for the given type for the
2756 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002757 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002758 !Update.getScalarVal()->getType()->isIntegerTy() ||
2759 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2760 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002761 X.getAddress().getElementType())) ||
2762 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002763 !Context.getTargetInfo().hasBuiltinAtomic(
2764 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002765 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002766
2767 llvm::AtomicRMWInst::BinOp RMWOp;
2768 switch (BO) {
2769 case BO_Add:
2770 RMWOp = llvm::AtomicRMWInst::Add;
2771 break;
2772 case BO_Sub:
2773 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002774 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002775 RMWOp = llvm::AtomicRMWInst::Sub;
2776 break;
2777 case BO_And:
2778 RMWOp = llvm::AtomicRMWInst::And;
2779 break;
2780 case BO_Or:
2781 RMWOp = llvm::AtomicRMWInst::Or;
2782 break;
2783 case BO_Xor:
2784 RMWOp = llvm::AtomicRMWInst::Xor;
2785 break;
2786 case BO_LT:
2787 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2788 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2789 : llvm::AtomicRMWInst::Max)
2790 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2791 : llvm::AtomicRMWInst::UMax);
2792 break;
2793 case BO_GT:
2794 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2795 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2796 : llvm::AtomicRMWInst::Min)
2797 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2798 : llvm::AtomicRMWInst::UMin);
2799 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002800 case BO_Assign:
2801 RMWOp = llvm::AtomicRMWInst::Xchg;
2802 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002803 case BO_Mul:
2804 case BO_Div:
2805 case BO_Rem:
2806 case BO_Shl:
2807 case BO_Shr:
2808 case BO_LAnd:
2809 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002810 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002811 case BO_PtrMemD:
2812 case BO_PtrMemI:
2813 case BO_LE:
2814 case BO_GE:
2815 case BO_EQ:
2816 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002817 case BO_AddAssign:
2818 case BO_SubAssign:
2819 case BO_AndAssign:
2820 case BO_OrAssign:
2821 case BO_XorAssign:
2822 case BO_MulAssign:
2823 case BO_DivAssign:
2824 case BO_RemAssign:
2825 case BO_ShlAssign:
2826 case BO_ShrAssign:
2827 case BO_Comma:
2828 llvm_unreachable("Unsupported atomic update operation");
2829 }
2830 auto *UpdateVal = Update.getScalarVal();
2831 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2832 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002833 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002834 X.getType()->hasSignedIntegerRepresentation());
2835 }
John McCall7f416cc2015-09-08 08:05:57 +00002836 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002837 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002838}
2839
Alexey Bataev5e018f92015-04-23 06:35:10 +00002840std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002841 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2842 llvm::AtomicOrdering AO, SourceLocation Loc,
2843 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2844 // Update expressions are allowed to have the following forms:
2845 // x binop= expr; -> xrval + expr;
2846 // x++, ++x -> xrval + 1;
2847 // x--, --x -> xrval - 1;
2848 // x = x binop expr; -> xrval binop expr
2849 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002850 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2851 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002852 if (X.isGlobalReg()) {
2853 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2854 // 'xrval'.
2855 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2856 } else {
2857 // Perform compare-and-swap procedure.
2858 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002859 }
2860 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002861 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002862}
2863
2864static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2865 const Expr *X, const Expr *E,
2866 const Expr *UE, bool IsXLHSInRHSPart,
2867 SourceLocation Loc) {
2868 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2869 "Update expr in 'atomic update' must be a binary operator.");
2870 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2871 // Update expressions are allowed to have the following forms:
2872 // x binop= expr; -> xrval + expr;
2873 // x++, ++x -> xrval + 1;
2874 // x--, --x -> xrval - 1;
2875 // x = x binop expr; -> xrval binop expr
2876 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002877 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002878 LValue XLValue = CGF.EmitLValue(X);
2879 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002880 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2881 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002882 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2883 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2884 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2885 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2886 auto Gen =
2887 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2888 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2889 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2890 return CGF.EmitAnyExpr(UE);
2891 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002892 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2893 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2894 // OpenMP, 2.12.6, atomic Construct
2895 // Any atomic construct with a seq_cst clause forces the atomically
2896 // performed operation to include an implicit flush operation without a
2897 // list.
2898 if (IsSeqCst)
2899 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2900}
2901
2902static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002903 QualType SourceType, QualType ResType,
2904 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002905 switch (CGF.getEvaluationKind(ResType)) {
2906 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002907 return RValue::get(
2908 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002909 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002910 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002911 return RValue::getComplex(Res.first, Res.second);
2912 }
2913 case TEK_Aggregate:
2914 break;
2915 }
2916 llvm_unreachable("Must be a scalar or complex.");
2917}
2918
2919static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2920 bool IsPostfixUpdate, const Expr *V,
2921 const Expr *X, const Expr *E,
2922 const Expr *UE, bool IsXLHSInRHSPart,
2923 SourceLocation Loc) {
2924 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2925 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2926 RValue NewVVal;
2927 LValue VLValue = CGF.EmitLValue(V);
2928 LValue XLValue = CGF.EmitLValue(X);
2929 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002930 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2931 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002932 QualType NewVValType;
2933 if (UE) {
2934 // 'x' is updated with some additional value.
2935 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2936 "Update expr in 'atomic capture' must be a binary operator.");
2937 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2938 // Update expressions are allowed to have the following forms:
2939 // x binop= expr; -> xrval + expr;
2940 // x++, ++x -> xrval + 1;
2941 // x--, --x -> xrval - 1;
2942 // x = x binop expr; -> xrval binop expr
2943 // x = expr Op x; - > expr binop xrval;
2944 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2945 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2946 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2947 NewVValType = XRValExpr->getType();
2948 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2949 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2950 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2951 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2952 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2953 RValue Res = CGF.EmitAnyExpr(UE);
2954 NewVVal = IsPostfixUpdate ? XRValue : Res;
2955 return Res;
2956 };
2957 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2958 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2959 if (Res.first) {
2960 // 'atomicrmw' instruction was generated.
2961 if (IsPostfixUpdate) {
2962 // Use old value from 'atomicrmw'.
2963 NewVVal = Res.second;
2964 } else {
2965 // 'atomicrmw' does not provide new value, so evaluate it using old
2966 // value of 'x'.
2967 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2968 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2969 NewVVal = CGF.EmitAnyExpr(UE);
2970 }
2971 }
2972 } else {
2973 // 'x' is simply rewritten with some 'expr'.
2974 NewVValType = X->getType().getNonReferenceType();
2975 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002976 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002977 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2978 NewVVal = XRValue;
2979 return ExprRValue;
2980 };
2981 // Try to perform atomicrmw xchg, otherwise simple exchange.
2982 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2983 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2984 Loc, Gen);
2985 if (Res.first) {
2986 // 'atomicrmw' instruction was generated.
2987 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2988 }
2989 }
2990 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002991 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002992 // OpenMP, 2.12.6, atomic Construct
2993 // Any atomic construct with a seq_cst clause forces the atomically
2994 // performed operation to include an implicit flush operation without a
2995 // list.
2996 if (IsSeqCst)
2997 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2998}
2999
Alexey Bataevb57056f2015-01-22 06:17:56 +00003000static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003001 bool IsSeqCst, bool IsPostfixUpdate,
3002 const Expr *X, const Expr *V, const Expr *E,
3003 const Expr *UE, bool IsXLHSInRHSPart,
3004 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003005 switch (Kind) {
3006 case OMPC_read:
3007 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3008 break;
3009 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003010 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3011 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003012 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003013 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003014 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3015 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003016 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003017 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3018 IsXLHSInRHSPart, Loc);
3019 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003020 case OMPC_if:
3021 case OMPC_final:
3022 case OMPC_num_threads:
3023 case OMPC_private:
3024 case OMPC_firstprivate:
3025 case OMPC_lastprivate:
3026 case OMPC_reduction:
3027 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003028 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003029 case OMPC_collapse:
3030 case OMPC_default:
3031 case OMPC_seq_cst:
3032 case OMPC_shared:
3033 case OMPC_linear:
3034 case OMPC_aligned:
3035 case OMPC_copyin:
3036 case OMPC_copyprivate:
3037 case OMPC_flush:
3038 case OMPC_proc_bind:
3039 case OMPC_schedule:
3040 case OMPC_ordered:
3041 case OMPC_nowait:
3042 case OMPC_untied:
3043 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003044 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003045 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003046 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003047 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003048 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003049 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003050 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003051 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003052 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003053 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003054 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003055 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003056 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003057 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003058 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003059 case OMPC_uniform:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003060 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3061 }
3062}
3063
3064void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003065 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003066 OpenMPClauseKind Kind = OMPC_unknown;
3067 for (auto *C : S.clauses()) {
3068 // Find first clause (skip seq_cst clause, if it is first).
3069 if (C->getClauseKind() != OMPC_seq_cst) {
3070 Kind = C->getClauseKind();
3071 break;
3072 }
3073 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003074
3075 const auto *CS =
3076 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003077 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003078 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003079 }
3080 // Processing for statements under 'atomic capture'.
3081 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3082 for (const auto *C : Compound->body()) {
3083 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3084 enterFullExpression(EWC);
3085 }
3086 }
3087 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003088
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003089 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3090 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003091 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003092 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3093 S.getV(), S.getExpr(), S.getUpdateExpr(),
3094 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003095 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003096 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003097 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003098}
3099
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003100std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
3101CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
3102 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
3103 bool IsOffloadEntry) {
3104 llvm::Function *OutlinedFn = nullptr;
3105 llvm::Constant *OutlinedFnID = nullptr;
3106 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3107 OMPPrivateScope PrivateScope(CGF);
3108 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3109 CGF.EmitOMPPrivateClause(S, PrivateScope);
3110 (void)PrivateScope.Privatize();
3111
3112 Action.Enter(CGF);
3113 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3114 };
3115 // Emit target region as a standalone region.
3116 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3117 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3118 return std::make_pair(OutlinedFn, OutlinedFnID);
3119}
3120
Samuel Antaobed3c462015-10-02 16:14:20 +00003121void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003122 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3123
3124 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003125 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003126
Samuel Antaoee8fb302016-01-06 13:42:12 +00003127 llvm::Function *Fn = nullptr;
3128 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003129
3130 // Check if we have any if clause associated with the directive.
3131 const Expr *IfCond = nullptr;
3132
3133 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3134 IfCond = C->getCondition();
3135 }
3136
3137 // Check if we have any device clause associated with the directive.
3138 const Expr *Device = nullptr;
3139 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3140 Device = C->getDevice();
3141 }
3142
Samuel Antaoee8fb302016-01-06 13:42:12 +00003143 // Check if we have an if clause whose conditional always evaluates to false
3144 // or if we do not have any targets specified. If so the target region is not
3145 // an offload entry point.
3146 bool IsOffloadEntry = true;
3147 if (IfCond) {
3148 bool Val;
3149 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3150 IsOffloadEntry = false;
3151 }
3152 if (CGM.getLangOpts().OMPTargetTriples.empty())
3153 IsOffloadEntry = false;
3154
3155 assert(CurFuncDecl && "No parent declaration for target region!");
3156 StringRef ParentName;
3157 // In case we have Ctors/Dtors we use the complete type variant to produce
3158 // the mangling of the device outlined kernel.
3159 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3160 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3161 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3162 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3163 else
3164 ParentName =
3165 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3166
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003167 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3168 CGM, S, ParentName, IsOffloadEntry);
3169 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003170 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003171 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003172}
3173
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003174static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3175 const OMPExecutableDirective &S,
3176 OpenMPDirectiveKind InnermostKind,
3177 const RegionCodeGenTy &CodeGen) {
3178 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003179 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3180 emitParallelOrTeamsOutlinedFunction(S,
3181 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003182
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003183 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3184 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3185 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3186 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003187 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3188 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003189
Carlo Bertollic6872252016-04-04 15:55:02 +00003190 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3191 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003192 }
3193
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003194 OMPLexicalScope Scope(CGF, S);
3195 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3196 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003197 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3198 CapturedVars);
3199}
3200
3201void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003202 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003203 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003204 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003205 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3206 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003207 (void)PrivateScope.Privatize();
3208 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3209 };
3210 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003211}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003212
3213void CodeGenFunction::EmitOMPCancellationPointDirective(
3214 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003215 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3216 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003217}
3218
Alexey Bataev80909872015-07-02 11:25:17 +00003219void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003220 const Expr *IfCond = nullptr;
3221 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3222 if (C->getNameModifier() == OMPD_unknown ||
3223 C->getNameModifier() == OMPD_cancel) {
3224 IfCond = C->getCondition();
3225 break;
3226 }
3227 }
3228 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003229 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003230}
3231
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003232CodeGenFunction::JumpDest
3233CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3234 if (Kind == OMPD_parallel || Kind == OMPD_task)
3235 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003236 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003237 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003238 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003239}
Michael Wong65f367f2015-07-21 13:44:28 +00003240
3241// Generate the instructions for '#pragma omp target data' directive.
3242void CodeGenFunction::EmitOMPTargetDataDirective(
3243 const OMPTargetDataDirective &S) {
Samuel Antaodf158d52016-04-27 22:58:19 +00003244 // The target data enclosed region is implemented just by emitting the
3245 // statement.
3246 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3247 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3248 };
3249
3250 // If we don't have target devices, don't bother emitting the data mapping
3251 // code.
3252 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
3253 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3254
3255 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_data,
3256 CodeGen);
3257 return;
3258 }
3259
3260 // Check if we have any if clause associated with the directive.
3261 const Expr *IfCond = nullptr;
3262 if (auto *C = S.getSingleClause<OMPIfClause>())
3263 IfCond = C->getCondition();
3264
3265 // Check if we have any device clause associated with the directive.
3266 const Expr *Device = nullptr;
3267 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3268 Device = C->getDevice();
3269
3270 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, CodeGen);
Michael Wong65f367f2015-07-21 13:44:28 +00003271}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003272
Samuel Antaodf67fc42016-01-19 19:15:56 +00003273void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3274 const OMPTargetEnterDataDirective &S) {
3275 // TODO: codegen for target enter data.
3276}
3277
Samuel Antao72590762016-01-19 20:04:50 +00003278void CodeGenFunction::EmitOMPTargetExitDataDirective(
3279 const OMPTargetExitDataDirective &S) {
3280 // TODO: codegen for target exit data.
3281}
3282
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003283void CodeGenFunction::EmitOMPTargetParallelDirective(
3284 const OMPTargetParallelDirective &S) {
3285 // TODO: codegen for target parallel.
3286}
3287
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003288void CodeGenFunction::EmitOMPTargetParallelForDirective(
3289 const OMPTargetParallelForDirective &S) {
3290 // TODO: codegen for target parallel for.
3291}
3292
Alexey Bataev7292c292016-04-25 12:22:29 +00003293/// Emit a helper variable and return corresponding lvalue.
3294static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3295 const ImplicitParamDecl *PVD,
3296 CodeGenFunction::OMPPrivateScope &Privates) {
3297 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3298 Privates.addPrivate(
3299 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3300}
3301
3302void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3303 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3304 // Emit outlined function for task construct.
3305 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3306 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3307 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3308 const Expr *IfCond = nullptr;
3309 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3310 if (C->getNameModifier() == OMPD_unknown ||
3311 C->getNameModifier() == OMPD_taskloop) {
3312 IfCond = C->getCondition();
3313 break;
3314 }
3315 }
3316 bool Nogroup = S.getSingleClause<OMPNogroupClause>();
3317 // TODO: Check if we should emit tied or untied task.
3318 // Check if the task is final
3319 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
3320 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3321 // If the condition constant folds and can be elided, try to avoid emitting
3322 // the condition and the dead arm of the if/else.
3323 auto *Cond = Clause->getCondition();
3324 bool CondConstant;
3325 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3326 Final.setInt(CondConstant);
3327 else
3328 Final.setPointer(EvaluateExprAsBool(Cond));
3329 } else {
3330 // By default the task is not final.
3331 Final.setInt(/*IntVal=*/false);
3332 }
3333
3334 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3335 // if (PreCond) {
3336 // for (IV in 0..LastIteration) BODY;
3337 // <Final counter/linear vars updates>;
3338 // }
3339 //
3340
3341 // Emit: if (PreCond) - begin.
3342 // If the condition constant folds and can be elided, avoid emitting the
3343 // whole loop.
3344 bool CondConstant;
3345 llvm::BasicBlock *ContBlock = nullptr;
3346 OMPLoopScope PreInitScope(CGF, S);
3347 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3348 if (!CondConstant)
3349 return;
3350 } else {
3351 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3352 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3353 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3354 CGF.getProfileCount(&S));
3355 CGF.EmitBlock(ThenBlock);
3356 CGF.incrementProfileCounter(&S);
3357 }
3358
3359 OMPPrivateScope LoopScope(CGF);
3360 // Emit helper vars inits.
3361 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3362 auto *I = CS->getCapturedDecl()->param_begin();
3363 auto *LBP = std::next(I, LowerBound);
3364 auto *UBP = std::next(I, UpperBound);
3365 auto *STP = std::next(I, Stride);
3366 auto *LIP = std::next(I, LastIter);
3367 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3368 LoopScope);
3369 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3370 LoopScope);
3371 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3372 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3373 LoopScope);
3374 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
3375 (void)LoopScope.Privatize();
3376 // Emit the loop iteration variable.
3377 const Expr *IVExpr = S.getIterationVariable();
3378 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3379 CGF.EmitVarDecl(*IVDecl);
3380 CGF.EmitIgnoredExpr(S.getInit());
3381
3382 // Emit the iterations count variable.
3383 // If it is not a variable, Sema decided to calculate iterations count on
3384 // each iteration (e.g., it is foldable into a constant).
3385 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3386 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3387 // Emit calculation of the iterations count.
3388 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3389 }
3390
3391 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3392 S.getInc(),
3393 [&S](CodeGenFunction &CGF) {
3394 CGF.EmitOMPLoopBody(S, JumpDest());
3395 CGF.EmitStopPoint(&S);
3396 },
3397 [](CodeGenFunction &) {});
3398 // Emit: if (PreCond) - end.
3399 if (ContBlock) {
3400 CGF.EmitBranch(ContBlock);
3401 CGF.EmitBlock(ContBlock, true);
3402 }
3403 };
3404 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, IfCond, &Final,
3405 Nogroup](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3406 const OMPPrivateDataTy &Data) {
3407 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3408 OMPLoopScope PreInitScope(CGF, S);
3409 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(
3410 CGF, S.getLocStart(), S, Data.Tied, Final, Nogroup,
3411 Data.NumberOfParts, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
3412 Data.PrivateVars, Data.PrivateCopies, Data.FirstprivateVars,
3413 Data.FirstprivateCopies, Data.FirstprivateInits);
3414 };
3415 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
3416 CodeGen);
3417 };
3418 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, /*Tied=*/true);
3419}
3420
Alexey Bataev49f6e782015-12-01 04:18:41 +00003421void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003422 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003423}
3424
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003425void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3426 const OMPTaskLoopSimdDirective &S) {
3427 // emit the code inside the construct for now
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003428 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003429 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003430 *this, OMPD_taskloop_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003431 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003432 CGF.EmitStmt(
3433 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3434 });
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003435}