blob: 322e8ff593f25fa0197ace19a1a475942de0e369 [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 Bataevf93095a2016-05-05 08:46:22 +0000743 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
744 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000745 auto IRef = C->varlist_begin();
746 auto IDestRef = C->destination_exprs().begin();
747 for (auto *IInit : C->private_copies()) {
748 // Keep the address of the original variable for future update at the end
749 // of the loop.
750 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000751 // Taskloops do not require additional initialization, it is done in
752 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000753 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
754 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000755 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000756 DeclRefExpr DRE(
757 const_cast<VarDecl *>(OrigVD),
758 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
759 OrigVD) != nullptr,
760 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
761 return EmitLValue(&DRE).getAddress();
762 });
763 // Check if the variable is also a firstprivate: in this case IInit is
764 // not generated. Initialization of this variable will happen in codegen
765 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000766 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000767 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000768 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
769 // Emit private VarDecl with copy init.
770 EmitDecl(*VD);
771 return GetAddrOfLocalVar(VD);
772 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000773 assert(IsRegistered &&
774 "lastprivate var already registered as private");
775 (void)IsRegistered;
776 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000777 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000778 ++IRef;
779 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000780 }
781 }
782 return HasAtLeastOneLastprivate;
783}
784
785void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000786 const OMPExecutableDirective &D, bool NoFinals,
787 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000788 if (!HaveInsertPoint())
789 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000790 // Emit following code:
791 // if (<IsLastIterCond>) {
792 // orig_var1 = private_orig_var1;
793 // ...
794 // orig_varn = private_orig_varn;
795 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000796 llvm::BasicBlock *ThenBB = nullptr;
797 llvm::BasicBlock *DoneBB = nullptr;
798 if (IsLastIterCond) {
799 ThenBB = createBasicBlock(".omp.lastprivate.then");
800 DoneBB = createBasicBlock(".omp.lastprivate.done");
801 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
802 EmitBlock(ThenBB);
803 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000804 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
805 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000806 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000807 auto IC = LoopDirective->counters().begin();
808 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000809 auto *D =
810 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
811 if (NoFinals)
812 AlreadyEmittedVars.insert(D);
813 else
814 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000815 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000816 }
817 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000818 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
819 auto IRef = C->varlist_begin();
820 auto ISrcRef = C->source_exprs().begin();
821 auto IDestRef = C->destination_exprs().begin();
822 for (auto *AssignOp : C->assignment_ops()) {
823 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
824 QualType Type = PrivateVD->getType();
825 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
826 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
827 // If lastprivate variable is a loop control variable for loop-based
828 // directive, update its value before copyin back to original
829 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000830 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
831 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000832 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
833 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
834 // Get the address of the original variable.
835 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
836 // Get the address of the private variable.
837 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
838 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
839 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000840 Address(Builder.CreateLoad(PrivateAddr),
841 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000842 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000843 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000844 ++IRef;
845 ++ISrcRef;
846 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000847 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000848 if (auto *PostUpdate = C->getPostUpdateExpr())
849 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000850 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000851 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000852 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000853}
854
Alexey Bataev31300ed2016-02-04 11:27:03 +0000855static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
856 LValue BaseLV, llvm::Value *Addr) {
857 Address Tmp = Address::invalid();
858 Address TopTmp = Address::invalid();
859 Address MostTopTmp = Address::invalid();
860 BaseTy = BaseTy.getNonReferenceType();
861 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
862 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
863 Tmp = CGF.CreateMemTemp(BaseTy);
864 if (TopTmp.isValid())
865 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
866 else
867 MostTopTmp = Tmp;
868 TopTmp = Tmp;
869 BaseTy = BaseTy->getPointeeType();
870 }
871 llvm::Type *Ty = BaseLV.getPointer()->getType();
872 if (Tmp.isValid())
873 Ty = Tmp.getElementType();
874 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
875 if (Tmp.isValid()) {
876 CGF.Builder.CreateStore(Addr, Tmp);
877 return MostTopTmp;
878 }
879 return Address(Addr, BaseLV.getAlignment());
880}
881
882static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
883 LValue BaseLV) {
884 BaseTy = BaseTy.getNonReferenceType();
885 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
886 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
887 if (auto *PtrTy = BaseTy->getAs<PointerType>())
888 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
889 else {
890 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
891 BaseTy->castAs<ReferenceType>());
892 }
893 BaseTy = BaseTy->getPointeeType();
894 }
895 return CGF.MakeAddrLValue(
896 Address(
897 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
898 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
899 BaseLV.getAlignment()),
900 BaseLV.getType(), BaseLV.getAlignmentSource());
901}
902
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000903void CodeGenFunction::EmitOMPReductionClauseInit(
904 const OMPExecutableDirective &D,
905 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000906 if (!HaveInsertPoint())
907 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000908 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000909 auto ILHS = C->lhs_exprs().begin();
910 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000911 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000912 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000913 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000914 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000915 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
916 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000917 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000918 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
919 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
920 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
921 Base = TempOASE->getBase()->IgnoreParenImpCasts();
922 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
923 Base = TempASE->getBase()->IgnoreParenImpCasts();
924 auto *DE = cast<DeclRefExpr>(Base);
925 auto *OrigVD = cast<VarDecl>(DE->getDecl());
926 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
927 auto OASELValueUB =
928 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
929 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000930 LValue BaseLValue =
931 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
932 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000933 // Store the address of the original variable associated with the LHS
934 // implicit variable.
935 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
936 return OASELValueLB.getAddress();
937 });
938 // Emit reduction copy.
939 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000940 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000941 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 // Emit VarDecl with copy init for arrays.
943 // Get the address of the original variable captured in current
944 // captured region.
945 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
946 OASELValueLB.getPointer());
947 Size = Builder.CreateNUWAdd(
948 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
949 CodeGenFunction::OpaqueValueMapping OpaqueMap(
950 *this, cast<OpaqueValueExpr>(
951 getContext()
952 .getAsVariableArrayType(PrivateVD->getType())
953 ->getSizeExpr()),
954 RValue::get(Size));
955 EmitVariablyModifiedType(PrivateVD->getType());
956 auto Emission = EmitAutoVarAlloca(*PrivateVD);
957 auto Addr = Emission.getAllocatedAddress();
958 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000959 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
960 DRD ? *IRed : Init,
961 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000962 EmitAutoVarCleanups(Emission);
963 // Emit private VarDecl with reduction init.
964 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
965 OASELValueLB.getPointer());
966 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000967 return castToBase(*this, OrigVD->getType(),
968 OASELValueLB.getType(), OriginalBaseLValue,
969 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000970 });
971 assert(IsRegistered && "private var already registered as private");
972 // Silence the warning about unused variable.
973 (void)IsRegistered;
974 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
975 return GetAddrOfLocalVar(PrivateVD);
976 });
977 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
978 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
979 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
980 Base = TempASE->getBase()->IgnoreParenImpCasts();
981 auto *DE = cast<DeclRefExpr>(Base);
982 auto *OrigVD = cast<VarDecl>(DE->getDecl());
983 auto ASELValue = EmitLValue(ASE);
984 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000985 LValue BaseLValue = loadToBegin(
986 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000987 // Store the address of the original variable associated with the LHS
988 // implicit variable.
989 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
990 return ASELValue.getAddress();
991 });
992 // Emit reduction copy.
993 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000994 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000995 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000996 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000997 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
998 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000999 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001000 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1001 ASELValue.getAddress(),
1002 ASELValue.getType());
1003 } else
1004 EmitAutoVarInit(Emission);
1005 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001006 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1007 ASELValue.getPointer());
1008 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001009 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1010 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001011 });
1012 assert(IsRegistered && "private var already registered as private");
1013 // Silence the warning about unused variable.
1014 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001015 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1016 return Builder.CreateElementBitCast(
1017 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1018 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001019 });
1020 } else {
1021 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001022 QualType Type = PrivateVD->getType();
1023 if (getContext().getAsArrayType(Type)) {
1024 // Store the address of the original variable associated with the LHS
1025 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001026 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1027 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1028 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001029 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001030 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001031 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001032 OriginalAddr = Builder.CreateElementBitCast(
1033 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1034 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001035 });
1036 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1037 if (Type->isVariablyModifiedType()) {
1038 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1039 *this, cast<OpaqueValueExpr>(
1040 getContext()
1041 .getAsVariableArrayType(PrivateVD->getType())
1042 ->getSizeExpr()),
1043 RValue::get(
1044 getTypeSize(OrigVD->getType().getNonReferenceType())));
1045 EmitVariablyModifiedType(Type);
1046 }
1047 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1048 auto Addr = Emission.getAllocatedAddress();
1049 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001050 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1051 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001052 EmitAutoVarCleanups(Emission);
1053 return Emission.getAllocatedAddress();
1054 });
1055 assert(IsRegistered && "private var already registered as private");
1056 // Silence the warning about unused variable.
1057 (void)IsRegistered;
1058 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1059 return Builder.CreateElementBitCast(
1060 GetAddrOfLocalVar(PrivateVD),
1061 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1062 });
1063 } else {
1064 // Store the address of the original variable associated with the LHS
1065 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001066 Address OriginalAddr = Address::invalid();
1067 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1068 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001069 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1070 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1071 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001072 OriginalAddr = EmitLValue(&DRE).getAddress();
1073 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001074 });
1075 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001076 bool IsRegistered = PrivateScope.addPrivate(
1077 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001078 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001079 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1080 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001081 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001082 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1083 OriginalAddr,
1084 PrivateVD->getType());
1085 } else
1086 EmitAutoVarInit(Emission);
1087 EmitAutoVarCleanups(Emission);
1088 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001089 });
1090 assert(IsRegistered && "private var already registered as private");
1091 // Silence the warning about unused variable.
1092 (void)IsRegistered;
1093 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1094 return GetAddrOfLocalVar(PrivateVD);
1095 });
1096 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001097 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001098 ++ILHS;
1099 ++IRHS;
1100 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001101 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001102 }
1103 }
1104}
1105
1106void CodeGenFunction::EmitOMPReductionClauseFinal(
1107 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001108 if (!HaveInsertPoint())
1109 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001110 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001111 llvm::SmallVector<const Expr *, 8> LHSExprs;
1112 llvm::SmallVector<const Expr *, 8> RHSExprs;
1113 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001114 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001115 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001116 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001117 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001118 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1119 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1120 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1121 }
1122 if (HasAtLeastOneReduction) {
1123 // Emit nowait reduction if nowait clause is present or directive is a
1124 // parallel directive (it always has implicit barrier).
1125 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001126 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001127 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001128 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1129 D.getDirectiveKind() == OMPD_simd,
1130 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001131 }
1132}
1133
Alexey Bataev61205072016-03-02 04:57:40 +00001134static void emitPostUpdateForReductionClause(
1135 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1136 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1137 if (!CGF.HaveInsertPoint())
1138 return;
1139 llvm::BasicBlock *DoneBB = nullptr;
1140 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1141 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1142 if (!DoneBB) {
1143 if (auto *Cond = CondGen(CGF)) {
1144 // If the first post-update expression is found, emit conditional
1145 // block if it was requested.
1146 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1147 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1148 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1149 CGF.EmitBlock(ThenBB);
1150 }
1151 }
1152 CGF.EmitIgnoredExpr(PostUpdate);
1153 }
1154 }
1155 if (DoneBB)
1156 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1157}
1158
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001159static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1160 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001161 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001162 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001163 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001164 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1165 emitParallelOrTeamsOutlinedFunction(S,
1166 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001167 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001168 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001169 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1170 /*IgnoreResultAssign*/ true);
1171 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1172 CGF, NumThreads, NumThreadsClause->getLocStart());
1173 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001174 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001175 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001176 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1177 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1178 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001179 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001180 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1181 if (C->getNameModifier() == OMPD_unknown ||
1182 C->getNameModifier() == OMPD_parallel) {
1183 IfCond = C->getCondition();
1184 break;
1185 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001186 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001187
1188 OMPLexicalScope Scope(CGF, S);
1189 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1190 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001191 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001192 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001193}
1194
1195void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001197 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001198 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001199 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001200 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1201 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001202 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001203 // propagation master's thread values of threadprivate variables to local
1204 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001205 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1206 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1207 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001208 }
1209 CGF.EmitOMPPrivateClause(S, PrivateScope);
1210 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1211 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001213 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001214 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001215 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001216 emitPostUpdateForReductionClause(
1217 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001218}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001219
Alexey Bataev0f34da12015-07-02 04:17:07 +00001220void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1221 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001222 RunCleanupsScope BodyScope(*this);
1223 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001224 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001225 EmitIgnoredExpr(I);
1226 }
Alexander Musman3276a272015-03-21 10:12:56 +00001227 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001228 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001229 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001230 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001231 }
1232
Alexander Musmana5f070a2014-10-01 06:03:56 +00001233 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001234 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001235 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001237 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001238 // The end (updates/cleanups).
1239 EmitBlock(Continue.getBlock());
1240 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001241}
1242
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001243void CodeGenFunction::EmitOMPInnerLoop(
1244 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1245 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001246 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1247 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001248 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001249
1250 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001251 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001252 EmitBlock(CondBlock);
1253 LoopStack.push(CondBlock);
1254
1255 // If there are any cleanups between here and the loop-exit scope,
1256 // create a block to stage a loop exit along.
1257 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001258 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001259 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001260
Alexander Musmand196ef22014-10-07 08:57:09 +00001261 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001262
Alexey Bataev2df54a02015-03-12 08:53:29 +00001263 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001264 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001265 if (ExitBlock != LoopExit.getBlock()) {
1266 EmitBlock(ExitBlock);
1267 EmitBranchThroughCleanup(LoopExit);
1268 }
1269
1270 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001271 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001272
1273 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001274 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1276
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001277 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001278
1279 // Emit "IV = IV + 1" and a back-edge to the condition block.
1280 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001281 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001282 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283 BreakContinueStack.pop_back();
1284 EmitBranch(CondBlock);
1285 LoopStack.pop();
1286 // Emit the fall-through block.
1287 EmitBlock(LoopExit.getBlock());
1288}
1289
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001290void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001291 if (!HaveInsertPoint())
1292 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001293 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001294 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001295 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001296 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001297 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1298 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1299 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1300 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1301 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1302 VD->getInit()->getType(), VK_LValue,
1303 VD->getInit()->getExprLoc());
1304 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1305 VD->getType()),
1306 /*capturedByInit=*/false);
1307 EmitAutoVarCleanups(Emission);
1308 } else
1309 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001310 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001311 // Emit the linear steps for the linear clauses.
1312 // If a step is not constant, it is pre-calculated before the loop.
1313 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1314 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001315 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001316 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001317 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001318 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001319 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001320}
1321
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001322void CodeGenFunction::EmitOMPLinearClauseFinal(
1323 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001324 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001325 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001326 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001327 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001328 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001329 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001330 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001331 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001332 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001333 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001334 // If the first post-update expression is found, emit conditional
1335 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001336 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1337 DoneBB = createBasicBlock(".omp.linear.pu.done");
1338 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1339 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001340 }
1341 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001342 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1343 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001344 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001345 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001346 Address OrigAddr = EmitLValue(&DRE).getAddress();
1347 CodeGenFunction::OMPPrivateScope VarScope(*this);
1348 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001349 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001350 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001351 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001352 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001353 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001354 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001355 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001356 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001357 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358}
1359
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001360static void emitAlignedClause(CodeGenFunction &CGF,
1361 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001362 if (!CGF.HaveInsertPoint())
1363 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001364 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001365 unsigned ClauseAlignment = 0;
1366 if (auto AlignmentExpr = Clause->getAlignment()) {
1367 auto AlignmentCI =
1368 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1369 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001370 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001371 for (auto E : Clause->varlists()) {
1372 unsigned Alignment = ClauseAlignment;
1373 if (Alignment == 0) {
1374 // OpenMP [2.8.1, Description]
1375 // If no optional parameter is specified, implementation-defined default
1376 // alignments for SIMD instructions on the target platforms are assumed.
1377 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001378 CGF.getContext()
1379 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1380 E->getType()->getPointeeType()))
1381 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001382 }
1383 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1384 "alignment is not power of 2");
1385 if (Alignment != 0) {
1386 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1387 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1388 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001389 }
1390 }
1391}
1392
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001393void CodeGenFunction::EmitOMPPrivateLoopCounters(
1394 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1395 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001396 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001397 auto I = S.private_counters().begin();
1398 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001399 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1400 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001402 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001403 if (!LocalDeclMap.count(PrivateVD)) {
1404 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1405 EmitAutoVarCleanups(VarEmission);
1406 }
1407 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1408 /*RefersToEnclosingVariableOrCapture=*/false,
1409 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1410 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001411 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1413 VD->hasGlobalStorage()) {
1414 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1415 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1416 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1417 E->getType(), VK_LValue, E->getExprLoc());
1418 return EmitLValue(&DRE).getAddress();
1419 });
1420 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001421 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001422 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001423}
1424
Alexey Bataev62dbb972015-04-22 11:59:37 +00001425static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1426 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1427 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001428 if (!CGF.HaveInsertPoint())
1429 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001430 {
1431 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001432 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001433 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001434 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001435 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001436 CGF.EmitIgnoredExpr(I);
1437 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001438 }
1439 // Check that loop is executed at least one time.
1440 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1441}
1442
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001443void CodeGenFunction::EmitOMPLinearClause(
1444 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1445 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001446 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001447 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1448 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1449 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1450 for (auto *C : LoopDirective->counters()) {
1451 SIMDLCVs.insert(
1452 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1453 }
1454 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001455 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001456 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001457 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001458 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1459 auto *PrivateVD =
1460 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001461 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1462 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1463 // Emit private VarDecl with copy init.
1464 EmitVarDecl(*PrivateVD);
1465 return GetAddrOfLocalVar(PrivateVD);
1466 });
1467 assert(IsRegistered && "linear var already registered as private");
1468 // Silence the warning about unused variable.
1469 (void)IsRegistered;
1470 } else
1471 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001472 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001473 }
1474 }
1475}
1476
Alexey Bataev45bfad52015-08-21 12:19:04 +00001477static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001478 const OMPExecutableDirective &D,
1479 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001480 if (!CGF.HaveInsertPoint())
1481 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001482 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001483 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1484 /*ignoreResult=*/true);
1485 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1486 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1487 // In presence of finite 'safelen', it may be unsafe to mark all
1488 // the memory instructions parallel, because loop-carried
1489 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001490 if (!IsMonotonic)
1491 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001492 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001493 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1494 /*ignoreResult=*/true);
1495 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001496 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001497 // In presence of finite 'safelen', it may be unsafe to mark all
1498 // the memory instructions parallel, because loop-carried
1499 // dependences of 'safelen' iterations are possible.
1500 CGF.LoopStack.setParallel(false);
1501 }
1502}
1503
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001504void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1505 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001506 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001507 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001508 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001509 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001510}
1511
Alexey Bataevef549a82016-03-09 09:49:09 +00001512void CodeGenFunction::EmitOMPSimdFinal(
1513 const OMPLoopDirective &D,
1514 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001515 if (!HaveInsertPoint())
1516 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001517 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001518 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001519 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001520 for (auto F : D.finals()) {
1521 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001522 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1523 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1524 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1525 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001526 if (!DoneBB) {
1527 if (auto *Cond = CondGen(*this)) {
1528 // If the first post-update expression is found, emit conditional
1529 // block if it was requested.
1530 auto *ThenBB = createBasicBlock(".omp.final.then");
1531 DoneBB = createBasicBlock(".omp.final.done");
1532 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1533 EmitBlock(ThenBB);
1534 }
1535 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001536 Address OrigAddr = Address::invalid();
1537 if (CED)
1538 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1539 else {
1540 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1541 /*RefersToEnclosingVariableOrCapture=*/false,
1542 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1543 OrigAddr = EmitLValue(&DRE).getAddress();
1544 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001545 OMPPrivateScope VarScope(*this);
1546 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001547 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001548 (void)VarScope.Privatize();
1549 EmitIgnoredExpr(F);
1550 }
1551 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001552 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001553 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001554 if (DoneBB)
1555 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001556}
1557
Alexander Musman515ad8c2014-05-22 08:54:05 +00001558void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001559 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001560 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001561 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001562 // for (IV in 0..LastIteration) BODY;
1563 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001564 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001565 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001566
Alexey Bataev62dbb972015-04-22 11:59:37 +00001567 // Emit: if (PreCond) - begin.
1568 // If the condition constant folds and can be elided, avoid emitting the
1569 // whole loop.
1570 bool CondConstant;
1571 llvm::BasicBlock *ContBlock = nullptr;
1572 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1573 if (!CondConstant)
1574 return;
1575 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001576 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1577 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001578 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1579 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001580 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001581 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001582 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001583
1584 // Emit the loop iteration variable.
1585 const Expr *IVExpr = S.getIterationVariable();
1586 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1587 CGF.EmitVarDecl(*IVDecl);
1588 CGF.EmitIgnoredExpr(S.getInit());
1589
1590 // Emit the iterations count variable.
1591 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001592 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001593 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1594 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1595 // Emit calculation of the iterations count.
1596 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001597 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001598
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001599 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001600
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001601 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001602 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001603 {
1604 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001605 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1606 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001607 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001608 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001609 bool HasLastprivateClause =
1610 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001611 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001612 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1613 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001614 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001615 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001616 CGF.EmitStopPoint(&S);
1617 },
1618 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001619 CGF.EmitOMPSimdFinal(
1620 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001621 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001622 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001623 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001624 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001625 emitPostUpdateForReductionClause(
1626 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001627 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001628 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001629 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001630 // Emit: if (PreCond) - end.
1631 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001632 CGF.EmitBranch(ContBlock);
1633 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001634 }
1635 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001636 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001637 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001638}
1639
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001640void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001641 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1642 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001643 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001644
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001645 const Expr *IVExpr = S.getIterationVariable();
1646 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1647 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1648
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001649 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1650
1651 // Start the loop with a block that tests the condition.
1652 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1653 EmitBlock(CondBlock);
1654 LoopStack.push(CondBlock);
1655
1656 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001657 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001658 // UB = min(UB, GlobalUB)
1659 EmitIgnoredExpr(S.getEnsureUpperBound());
1660 // IV = LB
1661 EmitIgnoredExpr(S.getInit());
1662 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001663 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001664 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001665 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1666 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001667 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001668
1669 // If there are any cleanups between here and the loop-exit scope,
1670 // create a block to stage a loop exit along.
1671 auto ExitBlock = LoopExit.getBlock();
1672 if (LoopScope.requiresCleanups())
1673 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1674
1675 auto LoopBody = createBasicBlock("omp.dispatch.body");
1676 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1677 if (ExitBlock != LoopExit.getBlock()) {
1678 EmitBlock(ExitBlock);
1679 EmitBranchThroughCleanup(LoopExit);
1680 }
1681 EmitBlock(LoopBody);
1682
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1684 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001685 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001686 EmitIgnoredExpr(S.getInit());
1687
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001688 // Create a block for the increment.
1689 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1690 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1691
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001692 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1693 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001694 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1695 LoopStack.setParallel(!IsMonotonic);
1696 else
1697 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001698
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001699 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001700 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1701 [&S, LoopExit](CodeGenFunction &CGF) {
1702 CGF.EmitOMPLoopBody(S, LoopExit);
1703 CGF.EmitStopPoint(&S);
1704 },
1705 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1706 if (Ordered) {
1707 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1708 CGF, Loc, IVSize, IVSigned);
1709 }
1710 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001711
1712 EmitBlock(Continue.getBlock());
1713 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001714 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001715 // Emit "LB = LB + Stride", "UB = UB + Stride".
1716 EmitIgnoredExpr(S.getNextLowerBound());
1717 EmitIgnoredExpr(S.getNextUpperBound());
1718 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001719
1720 EmitBranch(CondBlock);
1721 LoopStack.pop();
1722 // Emit the fall-through block.
1723 EmitBlock(LoopExit.getBlock());
1724
1725 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001726 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001727 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001728
1729}
1730
1731void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001732 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001733 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1734 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1735 auto &RT = CGM.getOpenMPRuntime();
1736
1737 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001738 const bool DynamicOrOrdered =
1739 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001740
1741 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001742 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1743 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001744 "static non-chunked schedule does not need outer loop");
1745
1746 // Emit outer loop.
1747 //
1748 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1749 // When schedule(dynamic,chunk_size) is specified, the iterations are
1750 // distributed to threads in the team in chunks as the threads request them.
1751 // Each thread executes a chunk of iterations, then requests another chunk,
1752 // until no chunks remain to be distributed. Each chunk contains chunk_size
1753 // iterations, except for the last chunk to be distributed, which may have
1754 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1755 //
1756 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1757 // to threads in the team in chunks as the executing threads request them.
1758 // Each thread executes a chunk of iterations, then requests another chunk,
1759 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1760 // each chunk is proportional to the number of unassigned iterations divided
1761 // by the number of threads in the team, decreasing to 1. For a chunk_size
1762 // with value k (greater than 1), the size of each chunk is determined in the
1763 // same way, with the restriction that the chunks do not contain fewer than k
1764 // iterations (except for the last chunk to be assigned, which may have fewer
1765 // than k iterations).
1766 //
1767 // When schedule(auto) is specified, the decision regarding scheduling is
1768 // delegated to the compiler and/or runtime system. The programmer gives the
1769 // implementation the freedom to choose any possible mapping of iterations to
1770 // threads in the team.
1771 //
1772 // When schedule(runtime) is specified, the decision regarding scheduling is
1773 // deferred until run time, and the schedule and chunk size are taken from the
1774 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1775 // implementation defined
1776 //
1777 // while(__kmpc_dispatch_next(&LB, &UB)) {
1778 // idx = LB;
1779 // while (idx <= UB) { BODY; ++idx;
1780 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1781 // } // inner loop
1782 // }
1783 //
1784 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1785 // When schedule(static, chunk_size) is specified, iterations are divided into
1786 // chunks of size chunk_size, and the chunks are assigned to the threads in
1787 // the team in a round-robin fashion in the order of the thread number.
1788 //
1789 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1790 // while (idx <= UB) { BODY; ++idx; } // inner loop
1791 // LB = LB + ST;
1792 // UB = UB + ST;
1793 // }
1794 //
1795
1796 const Expr *IVExpr = S.getIterationVariable();
1797 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1798 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1799
1800 if (DynamicOrOrdered) {
1801 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001802 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1803 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001804 } else {
1805 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1806 Ordered, IL, LB, UB, ST, Chunk);
1807 }
1808
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001809 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001810 ST, IL, Chunk);
1811}
1812
1813void CodeGenFunction::EmitOMPDistributeOuterLoop(
1814 OpenMPDistScheduleClauseKind ScheduleKind,
1815 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1816 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1817
1818 auto &RT = CGM.getOpenMPRuntime();
1819
1820 // Emit outer loop.
1821 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1822 // dynamic
1823 //
1824
1825 const Expr *IVExpr = S.getIterationVariable();
1826 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1827 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1828
1829 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1830 IVSize, IVSigned, /* Ordered = */ false,
1831 IL, LB, UB, ST, Chunk);
1832
1833 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1834 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001835}
1836
Alexander Musmanc6388682014-12-15 07:07:06 +00001837/// \brief Emit a helper variable and return corresponding lvalue.
1838static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1839 const DeclRefExpr *Helper) {
1840 auto VDecl = cast<VarDecl>(Helper->getDecl());
1841 CGF.EmitVarDecl(*VDecl);
1842 return CGF.EmitLValue(Helper);
1843}
1844
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001845namespace {
1846 struct ScheduleKindModifiersTy {
1847 OpenMPScheduleClauseKind Kind;
1848 OpenMPScheduleClauseModifier M1;
1849 OpenMPScheduleClauseModifier M2;
1850 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1851 OpenMPScheduleClauseModifier M1,
1852 OpenMPScheduleClauseModifier M2)
1853 : Kind(Kind), M1(M1), M2(M2) {}
1854 };
1855} // namespace
1856
Alexey Bataev38e89532015-04-16 04:54:05 +00001857bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001858 // Emit the loop iteration variable.
1859 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1860 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1861 EmitVarDecl(*IVDecl);
1862
1863 // Emit the iterations count variable.
1864 // If it is not a variable, Sema decided to calculate iterations count on each
1865 // iteration (e.g., it is foldable into a constant).
1866 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1867 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1868 // Emit calculation of the iterations count.
1869 EmitIgnoredExpr(S.getCalcLastIteration());
1870 }
1871
1872 auto &RT = CGM.getOpenMPRuntime();
1873
Alexey Bataev38e89532015-04-16 04:54:05 +00001874 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001875 // Check pre-condition.
1876 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001877 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001878 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001879 // If the condition constant folds and can be elided, avoid emitting the
1880 // whole loop.
1881 bool CondConstant;
1882 llvm::BasicBlock *ContBlock = nullptr;
1883 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1884 if (!CondConstant)
1885 return false;
1886 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001887 auto *ThenBlock = createBasicBlock("omp.precond.then");
1888 ContBlock = createBasicBlock("omp.precond.end");
1889 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001890 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001891 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001892 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001893 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001894
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001895 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001896 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001897 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001898 // Emit helper vars inits.
1899 LValue LB =
1900 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1901 LValue UB =
1902 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1903 LValue ST =
1904 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1905 LValue IL =
1906 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1907
Alexander Musmanc6388682014-12-15 07:07:06 +00001908 // Emit 'then' code.
1909 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001910 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001911 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1912 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001913 // initialization of firstprivate variables and post-update of
1914 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001915 CGM.getOpenMPRuntime().emitBarrierCall(
1916 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1917 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001918 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001919 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001920 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001921 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001922 EmitOMPPrivateLoopCounters(S, LoopScope);
1923 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001924 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001925
1926 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001927 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001928 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00001929 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001930 ScheduleKind.Schedule = C->getScheduleKind();
1931 ScheduleKind.M1 = C->getFirstScheduleModifier();
1932 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00001933 if (const auto *Ch = C->getChunkSize()) {
1934 Chunk = EmitScalarExpr(Ch);
1935 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1936 S.getIterationVariable()->getType(),
1937 S.getLocStart());
1938 }
1939 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001940 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1941 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001942 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001943 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1944 // If the static schedule kind is specified or if the ordered clause is
1945 // specified, and if no monotonic modifier is specified, the effect will
1946 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001947 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001948 /* Chunked */ Chunk != nullptr) &&
1949 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001950 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1951 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001952 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1953 // When no chunk_size is specified, the iteration space is divided into
1954 // chunks that are approximately equal in size, and at most one chunk is
1955 // distributed to each thread. Note that the size of the chunks is
1956 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001957 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1958 IVSize, IVSigned, Ordered,
1959 IL.getAddress(), LB.getAddress(),
1960 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001961 auto LoopExit =
1962 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001963 // UB = min(UB, GlobalUB);
1964 EmitIgnoredExpr(S.getEnsureUpperBound());
1965 // IV = LB;
1966 EmitIgnoredExpr(S.getInit());
1967 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001968 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1969 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001970 [&S, LoopExit](CodeGenFunction &CGF) {
1971 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001972 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001973 },
1974 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001975 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001976 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001977 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001978 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001979 const bool IsMonotonic =
1980 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
1981 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
1982 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1983 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001984 // Emit the outer loop, which requests its work chunk [LB..UB] from
1985 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001986 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001987 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1988 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001989 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001990 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1991 EmitOMPSimdFinal(S,
1992 [&](CodeGenFunction &CGF) -> llvm::Value * {
1993 return CGF.Builder.CreateIsNotNull(
1994 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1995 });
1996 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001997 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001998 // Emit post-update of the reduction variables if IsLastIter != 0.
1999 emitPostUpdateForReductionClause(
2000 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2001 return CGF.Builder.CreateIsNotNull(
2002 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2003 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002004 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2005 if (HasLastprivateClause)
2006 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002007 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2008 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002009 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002010 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002011 return CGF.Builder.CreateIsNotNull(
2012 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2013 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002014 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002015 if (ContBlock) {
2016 EmitBranch(ContBlock);
2017 EmitBlock(ContBlock, true);
2018 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002019 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002020 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002021}
2022
2023void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002024 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002025 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2026 PrePostActionTy &) {
2027 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2028 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002029 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002030 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002031 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2032 S.hasCancel());
2033 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002034
2035 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002036 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002037 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2038 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002039}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002040
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002041void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002042 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002043 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2044 PrePostActionTy &) {
2045 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2046 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002047 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002048 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002049 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2050 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002051
2052 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002053 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002054 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2055 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002056}
2057
Alexey Bataev2df54a02015-03-12 08:53:29 +00002058static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2059 const Twine &Name,
2060 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002061 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002062 if (Init)
2063 CGF.EmitScalarInit(Init, LVal);
2064 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002065}
2066
Alexey Bataev3392d762016-02-16 11:18:12 +00002067void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002068 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2069 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002070 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002071 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2072 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002073 auto &C = CGF.CGM.getContext();
2074 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2075 // Emit helper vars inits.
2076 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2077 CGF.Builder.getInt32(0));
2078 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2079 : CGF.Builder.getInt32(0);
2080 LValue UB =
2081 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2082 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2083 CGF.Builder.getInt32(1));
2084 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2085 CGF.Builder.getInt32(0));
2086 // Loop counter.
2087 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2088 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2089 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2090 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2091 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2092 // Generate condition for loop.
2093 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2094 OK_Ordinary, S.getLocStart(),
2095 /*fpContractable=*/false);
2096 // Increment for loop counter.
2097 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2098 S.getLocStart());
2099 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2100 // Iterate through all sections and emit a switch construct:
2101 // switch (IV) {
2102 // case 0:
2103 // <SectionStmt[0]>;
2104 // break;
2105 // ...
2106 // case <NumSection> - 1:
2107 // <SectionStmt[<NumSection> - 1]>;
2108 // break;
2109 // }
2110 // .omp.sections.exit:
2111 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2112 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2113 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2114 CS == nullptr ? 1 : CS->size());
2115 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002116 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002117 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002118 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2119 CGF.EmitBlock(CaseBB);
2120 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002121 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002122 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002123 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002124 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002125 } else {
2126 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2127 CGF.EmitBlock(CaseBB);
2128 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2129 CGF.EmitStmt(Stmt);
2130 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002131 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002132 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002133 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002134
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002135 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2136 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002137 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002138 // initialization of firstprivate variables and post-update of lastprivate
2139 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002140 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2141 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2142 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002143 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002144 CGF.EmitOMPPrivateClause(S, LoopScope);
2145 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2146 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2147 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002148
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002149 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002150 OpenMPScheduleTy ScheduleKind;
2151 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002152 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002153 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002154 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2155 UB.getAddress(), ST.getAddress());
2156 // UB = min(UB, GlobalUB);
2157 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2158 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2159 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2160 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2161 // IV = LB;
2162 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2163 // while (idx <= UB) { BODY; ++idx; }
2164 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2165 [](CodeGenFunction &) {});
2166 // Tell the runtime we are done.
2167 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2168 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002169 // Emit post-update of the reduction variables if IsLastIter != 0.
2170 emitPostUpdateForReductionClause(
2171 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2172 return CGF.Builder.CreateIsNotNull(
2173 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2174 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002175
2176 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2177 if (HasLastprivates)
2178 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002179 S, /*NoFinals=*/false,
2180 CGF.Builder.CreateIsNotNull(
2181 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002182 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002183
2184 bool HasCancel = false;
2185 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2186 HasCancel = OSD->hasCancel();
2187 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2188 HasCancel = OPSD->hasCancel();
2189 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2190 HasCancel);
2191 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2192 // clause. Otherwise the barrier will be generated by the codegen for the
2193 // directive.
2194 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002195 // Emit implicit barrier to synchronize threads and avoid data races on
2196 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002197 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2198 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002199 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002200}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002201
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002202void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002203 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002204 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002205 EmitSections(S);
2206 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002207 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002208 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002209 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2210 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002211 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002212}
2213
2214void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002215 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002216 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002217 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002218 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002219 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2220 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002221}
2222
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002223void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002224 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002225 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002226 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002227 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002228 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002229 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002230 // Build a list of copyprivate variables along with helper expressions
2231 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002232 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002233 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002234 DestExprs.append(C->destination_exprs().begin(),
2235 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002236 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002237 AssignmentOps.append(C->assignment_ops().begin(),
2238 C->assignment_ops().end());
2239 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002240 // Emit code for 'single' region along with 'copyprivate' clauses
2241 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2242 Action.Enter(CGF);
2243 OMPPrivateScope SingleScope(CGF);
2244 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2245 CGF.EmitOMPPrivateClause(S, SingleScope);
2246 (void)SingleScope.Privatize();
2247 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2248 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002249 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002250 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002251 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2252 CopyprivateVars, DestExprs,
2253 SrcExprs, AssignmentOps);
2254 }
2255 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2256 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002257 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002258 CGM.getOpenMPRuntime().emitBarrierCall(
2259 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002260 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002261 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002262}
2263
Alexey Bataev8d690652014-12-04 07:23:53 +00002264void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002265 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2266 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002267 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002268 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002269 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002270 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002271}
2272
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002273void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002274 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2275 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002276 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002277 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002278 Expr *Hint = nullptr;
2279 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2280 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002281 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002282 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2283 S.getDirectiveName().getAsString(),
2284 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002285}
2286
Alexey Bataev671605e2015-04-13 05:28:11 +00002287void CodeGenFunction::EmitOMPParallelForDirective(
2288 const OMPParallelForDirective &S) {
2289 // Emit directive as a combined directive that consists of two implicit
2290 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002291 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002292 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002293 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002294 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002295}
2296
Alexander Musmane4e893b2014-09-23 09:33:00 +00002297void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002298 const OMPParallelForSimdDirective &S) {
2299 // Emit directive as a combined directive that consists of two implicit
2300 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002301 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002302 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002303 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002304 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002305}
2306
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002307void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002308 const OMPParallelSectionsDirective &S) {
2309 // Emit directive as a combined directive that consists of two implicit
2310 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002311 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2312 CGF.EmitSections(S);
2313 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002314 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002315}
2316
Alexey Bataev7292c292016-04-25 12:22:29 +00002317void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2318 const RegionCodeGenTy &BodyGen,
2319 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002320 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002321 // Emit outlined function for task construct.
2322 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002323 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002324 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002325 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002326 // Check if the task is final
2327 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2328 // If the condition constant folds and can be elided, try to avoid emitting
2329 // the condition and the dead arm of the if/else.
2330 auto *Cond = Clause->getCondition();
2331 bool CondConstant;
2332 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2333 Data.Final.setInt(CondConstant);
2334 else
2335 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2336 } else {
2337 // By default the task is not final.
2338 Data.Final.setInt(/*IntVal=*/false);
2339 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002340 // The first function argument for tasks is a thread id, the second one is a
2341 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002342 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2343 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002344 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002345 auto IRef = C->varlist_begin();
2346 for (auto *IInit : C->private_copies()) {
2347 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2348 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002349 Data.PrivateVars.push_back(*IRef);
2350 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002351 }
2352 ++IRef;
2353 }
2354 }
2355 EmittedAsPrivate.clear();
2356 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002357 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002358 auto IRef = C->varlist_begin();
2359 auto IElemInitRef = C->inits().begin();
2360 for (auto *IInit : C->private_copies()) {
2361 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2362 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002363 Data.FirstprivateVars.push_back(*IRef);
2364 Data.FirstprivateCopies.push_back(IInit);
2365 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002366 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002367 ++IRef;
2368 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002369 }
2370 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002371 // Get list of lastprivate variables (for taskloops).
2372 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2373 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2374 auto IRef = C->varlist_begin();
2375 auto ID = C->destination_exprs().begin();
2376 for (auto *IInit : C->private_copies()) {
2377 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2378 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2379 Data.LastprivateVars.push_back(*IRef);
2380 Data.LastprivateCopies.push_back(IInit);
2381 }
2382 LastprivateDstsOrigs.insert(
2383 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2384 cast<DeclRefExpr>(*IRef)});
2385 ++IRef;
2386 ++ID;
2387 }
2388 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002389 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002390 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2391 for (auto *IRef : C->varlists())
2392 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevf93095a2016-05-05 08:46:22 +00002393 auto &&CodeGen = [PartId, &S, &Data, CS, &BodyGen, &LastprivateDstsOrigs](
2394 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002395 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002396 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002397 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2398 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002399 auto *CopyFn = CGF.Builder.CreateLoad(
2400 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2401 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2402 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2403 // Map privates.
2404 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2405 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2406 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002407 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002408 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2409 Address PrivatePtr = CGF.CreateMemTemp(
2410 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2411 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2412 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002413 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002414 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002415 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2416 Address PrivatePtr =
2417 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2418 ".firstpriv.ptr.addr");
2419 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2420 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002421 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002422 for (auto *E : Data.LastprivateVars) {
2423 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2424 Address PrivatePtr =
2425 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2426 ".lastpriv.ptr.addr");
2427 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2428 CallArgs.push_back(PrivatePtr.getPointer());
2429 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002430 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002431 for (auto &&Pair : LastprivateDstsOrigs) {
2432 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2433 DeclRefExpr DRE(
2434 const_cast<VarDecl *>(OrigVD),
2435 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2436 OrigVD) != nullptr,
2437 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2438 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2439 return CGF.EmitLValue(&DRE).getAddress();
2440 });
2441 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002442 for (auto &&Pair : PrivatePtrs) {
2443 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2444 CGF.getContext().getDeclAlign(Pair.first));
2445 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2446 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002447 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002448 (void)Scope.Privatize();
2449
2450 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002451 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002452 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002453 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2454 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2455 Data.NumberOfParts);
2456 OMPLexicalScope Scope(*this, S);
2457 TaskGen(*this, OutlinedFn, Data);
2458}
2459
2460void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2461 // Emit outlined function for task construct.
2462 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2463 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002464 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002465 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002466 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2467 if (C->getNameModifier() == OMPD_unknown ||
2468 C->getNameModifier() == OMPD_task) {
2469 IfCond = C->getCondition();
2470 break;
2471 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002472 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002473
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002474 OMPTaskDataTy Data;
2475 // Check if we should emit tied or untied task.
2476 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002477 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2478 CGF.EmitStmt(CS->getCapturedStmt());
2479 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002480 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002481 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002482 const OMPTaskDataTy &Data) {
2483 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2484 SharedsTy, CapturedStruct, IfCond,
2485 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002486 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002487 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002488}
2489
Alexey Bataev9f797f32015-02-05 05:57:51 +00002490void CodeGenFunction::EmitOMPTaskyieldDirective(
2491 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002492 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002493}
2494
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002495void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002496 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002497}
2498
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002499void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2500 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002501}
2502
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002503void CodeGenFunction::EmitOMPTaskgroupDirective(
2504 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002505 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2506 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002507 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002508 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002509 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002510 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2511}
2512
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002513void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002514 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002515 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002516 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2517 FlushClause->varlist_end());
2518 }
2519 return llvm::None;
2520 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002521}
2522
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002523void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2524 // Emit the loop iteration variable.
2525 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2526 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2527 EmitVarDecl(*IVDecl);
2528
2529 // Emit the iterations count variable.
2530 // If it is not a variable, Sema decided to calculate iterations count on each
2531 // iteration (e.g., it is foldable into a constant).
2532 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2533 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2534 // Emit calculation of the iterations count.
2535 EmitIgnoredExpr(S.getCalcLastIteration());
2536 }
2537
2538 auto &RT = CGM.getOpenMPRuntime();
2539
2540 // Check pre-condition.
2541 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002542 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002543 // Skip the entire loop if we don't meet the precondition.
2544 // If the condition constant folds and can be elided, avoid emitting the
2545 // whole loop.
2546 bool CondConstant;
2547 llvm::BasicBlock *ContBlock = nullptr;
2548 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2549 if (!CondConstant)
2550 return;
2551 } else {
2552 auto *ThenBlock = createBasicBlock("omp.precond.then");
2553 ContBlock = createBasicBlock("omp.precond.end");
2554 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2555 getProfileCount(&S));
2556 EmitBlock(ThenBlock);
2557 incrementProfileCounter(&S);
2558 }
2559
2560 // Emit 'then' code.
2561 {
2562 // Emit helper vars inits.
2563 LValue LB =
2564 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2565 LValue UB =
2566 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2567 LValue ST =
2568 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2569 LValue IL =
2570 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2571
2572 OMPPrivateScope LoopScope(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002573 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002574 (void)LoopScope.Privatize();
2575
2576 // Detect the distribute schedule kind and chunk.
2577 llvm::Value *Chunk = nullptr;
2578 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2579 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2580 ScheduleKind = C->getDistScheduleKind();
2581 if (const auto *Ch = C->getChunkSize()) {
2582 Chunk = EmitScalarExpr(Ch);
2583 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2584 S.getIterationVariable()->getType(),
2585 S.getLocStart());
2586 }
2587 }
2588 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2589 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2590
2591 // OpenMP [2.10.8, distribute Construct, Description]
2592 // If dist_schedule is specified, kind must be static. If specified,
2593 // iterations are divided into chunks of size chunk_size, chunks are
2594 // assigned to the teams of the league in a round-robin fashion in the
2595 // order of the team number. When no chunk_size is specified, the
2596 // iteration space is divided into chunks that are approximately equal
2597 // in size, and at most one chunk is distributed to each team of the
2598 // league. The size of the chunks is unspecified in this case.
2599 if (RT.isStaticNonchunked(ScheduleKind,
2600 /* Chunked */ Chunk != nullptr)) {
2601 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2602 IVSize, IVSigned, /* Ordered = */ false,
2603 IL.getAddress(), LB.getAddress(),
2604 UB.getAddress(), ST.getAddress());
2605 auto LoopExit =
2606 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2607 // UB = min(UB, GlobalUB);
2608 EmitIgnoredExpr(S.getEnsureUpperBound());
2609 // IV = LB;
2610 EmitIgnoredExpr(S.getInit());
2611 // while (idx <= UB) { BODY; ++idx; }
2612 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2613 S.getInc(),
2614 [&S, LoopExit](CodeGenFunction &CGF) {
2615 CGF.EmitOMPLoopBody(S, LoopExit);
2616 CGF.EmitStopPoint(&S);
2617 },
2618 [](CodeGenFunction &) {});
2619 EmitBlock(LoopExit.getBlock());
2620 // Tell the runtime we are done.
2621 RT.emitForStaticFinish(*this, S.getLocStart());
2622 } else {
2623 // Emit the outer loop, which requests its work chunk [LB..UB] from
2624 // runtime and runs the inner loop to process it.
2625 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2626 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2627 IL.getAddress(), Chunk);
2628 }
2629 }
2630
2631 // We're now done with the loop, so jump to the continuation block.
2632 if (ContBlock) {
2633 EmitBranch(ContBlock);
2634 EmitBlock(ContBlock, true);
2635 }
2636 }
2637}
2638
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002639void CodeGenFunction::EmitOMPDistributeDirective(
2640 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002641 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002642 CGF.EmitOMPDistributeLoop(S);
2643 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002644 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002645 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2646 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002647}
2648
Alexey Bataev5f600d62015-09-29 03:48:57 +00002649static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2650 const CapturedStmt *S) {
2651 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2652 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2653 CGF.CapturedStmtInfo = &CapStmtInfo;
2654 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2655 Fn->addFnAttr(llvm::Attribute::NoInline);
2656 return Fn;
2657}
2658
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002659void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002660 if (!S.getAssociatedStmt())
2661 return;
Alexey Bataev5f600d62015-09-29 03:48:57 +00002662 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002663 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2664 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002665 if (C) {
2666 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2667 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2668 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2669 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2670 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2671 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002672 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002673 CGF.EmitStmt(
2674 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2675 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002676 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002677 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002678 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002679}
2680
Alexey Bataevb57056f2015-01-22 06:17:56 +00002681static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002682 QualType SrcType, QualType DestType,
2683 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002684 assert(CGF.hasScalarEvaluationKind(DestType) &&
2685 "DestType must have scalar evaluation kind.");
2686 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2687 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002688 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2689 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002690 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002691 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002692}
2693
2694static CodeGenFunction::ComplexPairTy
2695convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002696 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002697 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2698 "DestType must have complex evaluation kind.");
2699 CodeGenFunction::ComplexPairTy ComplexVal;
2700 if (Val.isScalar()) {
2701 // Convert the input element to the element type of the complex.
2702 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002703 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2704 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002705 ComplexVal = CodeGenFunction::ComplexPairTy(
2706 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2707 } else {
2708 assert(Val.isComplex() && "Must be a scalar or complex.");
2709 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2710 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2711 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002712 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002713 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002714 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002715 }
2716 return ComplexVal;
2717}
2718
Alexey Bataev5e018f92015-04-23 06:35:10 +00002719static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2720 LValue LVal, RValue RVal) {
2721 if (LVal.isGlobalReg()) {
2722 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2723 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002724 CGF.EmitAtomicStore(RVal, LVal,
2725 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2726 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002727 LVal.isVolatile(), /*IsInit=*/false);
2728 }
2729}
2730
Alexey Bataev8524d152016-01-21 12:35:58 +00002731void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2732 QualType RValTy, SourceLocation Loc) {
2733 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002734 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002735 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2736 *this, RVal, RValTy, LVal.getType(), Loc)),
2737 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002738 break;
2739 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002740 EmitStoreOfComplex(
2741 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002742 /*isInit=*/false);
2743 break;
2744 case TEK_Aggregate:
2745 llvm_unreachable("Must be a scalar or complex.");
2746 }
2747}
2748
Alexey Bataevb57056f2015-01-22 06:17:56 +00002749static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2750 const Expr *X, const Expr *V,
2751 SourceLocation Loc) {
2752 // v = x;
2753 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2754 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2755 LValue XLValue = CGF.EmitLValue(X);
2756 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002757 RValue Res = XLValue.isGlobalReg()
2758 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00002759 : CGF.EmitAtomicLoad(
2760 XLValue, Loc,
2761 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2762 : llvm::AtomicOrdering::Monotonic,
2763 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002764 // OpenMP, 2.12.6, atomic Construct
2765 // Any atomic construct with a seq_cst clause forces the atomically
2766 // performed operation to include an implicit flush operation without a
2767 // list.
2768 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002769 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002770 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002771}
2772
Alexey Bataevb8329262015-02-27 06:33:30 +00002773static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2774 const Expr *X, const Expr *E,
2775 SourceLocation Loc) {
2776 // x = expr;
2777 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002778 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002779 // OpenMP, 2.12.6, atomic Construct
2780 // Any atomic construct with a seq_cst clause forces the atomically
2781 // performed operation to include an implicit flush operation without a
2782 // list.
2783 if (IsSeqCst)
2784 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2785}
2786
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002787static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2788 RValue Update,
2789 BinaryOperatorKind BO,
2790 llvm::AtomicOrdering AO,
2791 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002792 auto &Context = CGF.CGM.getContext();
2793 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002794 // expression is simple and atomic is allowed for the given type for the
2795 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002796 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002797 !Update.getScalarVal()->getType()->isIntegerTy() ||
2798 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2799 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002800 X.getAddress().getElementType())) ||
2801 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002802 !Context.getTargetInfo().hasBuiltinAtomic(
2803 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002804 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002805
2806 llvm::AtomicRMWInst::BinOp RMWOp;
2807 switch (BO) {
2808 case BO_Add:
2809 RMWOp = llvm::AtomicRMWInst::Add;
2810 break;
2811 case BO_Sub:
2812 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002813 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002814 RMWOp = llvm::AtomicRMWInst::Sub;
2815 break;
2816 case BO_And:
2817 RMWOp = llvm::AtomicRMWInst::And;
2818 break;
2819 case BO_Or:
2820 RMWOp = llvm::AtomicRMWInst::Or;
2821 break;
2822 case BO_Xor:
2823 RMWOp = llvm::AtomicRMWInst::Xor;
2824 break;
2825 case BO_LT:
2826 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2827 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2828 : llvm::AtomicRMWInst::Max)
2829 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2830 : llvm::AtomicRMWInst::UMax);
2831 break;
2832 case BO_GT:
2833 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2834 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2835 : llvm::AtomicRMWInst::Min)
2836 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2837 : llvm::AtomicRMWInst::UMin);
2838 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002839 case BO_Assign:
2840 RMWOp = llvm::AtomicRMWInst::Xchg;
2841 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002842 case BO_Mul:
2843 case BO_Div:
2844 case BO_Rem:
2845 case BO_Shl:
2846 case BO_Shr:
2847 case BO_LAnd:
2848 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002849 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002850 case BO_PtrMemD:
2851 case BO_PtrMemI:
2852 case BO_LE:
2853 case BO_GE:
2854 case BO_EQ:
2855 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002856 case BO_AddAssign:
2857 case BO_SubAssign:
2858 case BO_AndAssign:
2859 case BO_OrAssign:
2860 case BO_XorAssign:
2861 case BO_MulAssign:
2862 case BO_DivAssign:
2863 case BO_RemAssign:
2864 case BO_ShlAssign:
2865 case BO_ShrAssign:
2866 case BO_Comma:
2867 llvm_unreachable("Unsupported atomic update operation");
2868 }
2869 auto *UpdateVal = Update.getScalarVal();
2870 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2871 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002872 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002873 X.getType()->hasSignedIntegerRepresentation());
2874 }
John McCall7f416cc2015-09-08 08:05:57 +00002875 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002876 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002877}
2878
Alexey Bataev5e018f92015-04-23 06:35:10 +00002879std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002880 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2881 llvm::AtomicOrdering AO, SourceLocation Loc,
2882 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2883 // Update expressions are allowed to have the following forms:
2884 // x binop= expr; -> xrval + expr;
2885 // x++, ++x -> xrval + 1;
2886 // x--, --x -> xrval - 1;
2887 // x = x binop expr; -> xrval binop expr
2888 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002889 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2890 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002891 if (X.isGlobalReg()) {
2892 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2893 // 'xrval'.
2894 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2895 } else {
2896 // Perform compare-and-swap procedure.
2897 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002898 }
2899 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002900 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002901}
2902
2903static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2904 const Expr *X, const Expr *E,
2905 const Expr *UE, bool IsXLHSInRHSPart,
2906 SourceLocation Loc) {
2907 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2908 "Update expr in 'atomic update' must be a binary operator.");
2909 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2910 // Update expressions are allowed to have the following forms:
2911 // x binop= expr; -> xrval + expr;
2912 // x++, ++x -> xrval + 1;
2913 // x--, --x -> xrval - 1;
2914 // x = x binop expr; -> xrval binop expr
2915 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002916 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002917 LValue XLValue = CGF.EmitLValue(X);
2918 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002919 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2920 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002921 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2922 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2923 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2924 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2925 auto Gen =
2926 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2927 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2928 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2929 return CGF.EmitAnyExpr(UE);
2930 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002931 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2932 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2933 // OpenMP, 2.12.6, atomic Construct
2934 // Any atomic construct with a seq_cst clause forces the atomically
2935 // performed operation to include an implicit flush operation without a
2936 // list.
2937 if (IsSeqCst)
2938 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2939}
2940
2941static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002942 QualType SourceType, QualType ResType,
2943 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002944 switch (CGF.getEvaluationKind(ResType)) {
2945 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002946 return RValue::get(
2947 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002948 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002949 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002950 return RValue::getComplex(Res.first, Res.second);
2951 }
2952 case TEK_Aggregate:
2953 break;
2954 }
2955 llvm_unreachable("Must be a scalar or complex.");
2956}
2957
2958static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2959 bool IsPostfixUpdate, const Expr *V,
2960 const Expr *X, const Expr *E,
2961 const Expr *UE, bool IsXLHSInRHSPart,
2962 SourceLocation Loc) {
2963 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2964 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2965 RValue NewVVal;
2966 LValue VLValue = CGF.EmitLValue(V);
2967 LValue XLValue = CGF.EmitLValue(X);
2968 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002969 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2970 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002971 QualType NewVValType;
2972 if (UE) {
2973 // 'x' is updated with some additional value.
2974 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2975 "Update expr in 'atomic capture' must be a binary operator.");
2976 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2977 // Update expressions are allowed to have the following forms:
2978 // x binop= expr; -> xrval + expr;
2979 // x++, ++x -> xrval + 1;
2980 // x--, --x -> xrval - 1;
2981 // x = x binop expr; -> xrval binop expr
2982 // x = expr Op x; - > expr binop xrval;
2983 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2984 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2985 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2986 NewVValType = XRValExpr->getType();
2987 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2988 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2989 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2990 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2991 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2992 RValue Res = CGF.EmitAnyExpr(UE);
2993 NewVVal = IsPostfixUpdate ? XRValue : Res;
2994 return Res;
2995 };
2996 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2997 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2998 if (Res.first) {
2999 // 'atomicrmw' instruction was generated.
3000 if (IsPostfixUpdate) {
3001 // Use old value from 'atomicrmw'.
3002 NewVVal = Res.second;
3003 } else {
3004 // 'atomicrmw' does not provide new value, so evaluate it using old
3005 // value of 'x'.
3006 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3007 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3008 NewVVal = CGF.EmitAnyExpr(UE);
3009 }
3010 }
3011 } else {
3012 // 'x' is simply rewritten with some 'expr'.
3013 NewVValType = X->getType().getNonReferenceType();
3014 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003015 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003016 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
3017 NewVVal = XRValue;
3018 return ExprRValue;
3019 };
3020 // Try to perform atomicrmw xchg, otherwise simple exchange.
3021 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3022 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3023 Loc, Gen);
3024 if (Res.first) {
3025 // 'atomicrmw' instruction was generated.
3026 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3027 }
3028 }
3029 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003030 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003031 // OpenMP, 2.12.6, atomic Construct
3032 // Any atomic construct with a seq_cst clause forces the atomically
3033 // performed operation to include an implicit flush operation without a
3034 // list.
3035 if (IsSeqCst)
3036 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3037}
3038
Alexey Bataevb57056f2015-01-22 06:17:56 +00003039static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003040 bool IsSeqCst, bool IsPostfixUpdate,
3041 const Expr *X, const Expr *V, const Expr *E,
3042 const Expr *UE, bool IsXLHSInRHSPart,
3043 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003044 switch (Kind) {
3045 case OMPC_read:
3046 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3047 break;
3048 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003049 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3050 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003051 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003052 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003053 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3054 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003055 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003056 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3057 IsXLHSInRHSPart, Loc);
3058 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003059 case OMPC_if:
3060 case OMPC_final:
3061 case OMPC_num_threads:
3062 case OMPC_private:
3063 case OMPC_firstprivate:
3064 case OMPC_lastprivate:
3065 case OMPC_reduction:
3066 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003067 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003068 case OMPC_collapse:
3069 case OMPC_default:
3070 case OMPC_seq_cst:
3071 case OMPC_shared:
3072 case OMPC_linear:
3073 case OMPC_aligned:
3074 case OMPC_copyin:
3075 case OMPC_copyprivate:
3076 case OMPC_flush:
3077 case OMPC_proc_bind:
3078 case OMPC_schedule:
3079 case OMPC_ordered:
3080 case OMPC_nowait:
3081 case OMPC_untied:
3082 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003083 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003084 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003085 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003086 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003087 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003088 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003089 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003090 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003091 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003092 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003093 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003094 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003095 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003096 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003097 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003098 case OMPC_uniform:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003099 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3100 }
3101}
3102
3103void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003104 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003105 OpenMPClauseKind Kind = OMPC_unknown;
3106 for (auto *C : S.clauses()) {
3107 // Find first clause (skip seq_cst clause, if it is first).
3108 if (C->getClauseKind() != OMPC_seq_cst) {
3109 Kind = C->getClauseKind();
3110 break;
3111 }
3112 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003113
3114 const auto *CS =
3115 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003116 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003117 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003118 }
3119 // Processing for statements under 'atomic capture'.
3120 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3121 for (const auto *C : Compound->body()) {
3122 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3123 enterFullExpression(EWC);
3124 }
3125 }
3126 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003127
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003128 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3129 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003130 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003131 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3132 S.getV(), S.getExpr(), S.getUpdateExpr(),
3133 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003134 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003135 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003136 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003137}
3138
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003139std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
3140CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
3141 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
3142 bool IsOffloadEntry) {
3143 llvm::Function *OutlinedFn = nullptr;
3144 llvm::Constant *OutlinedFnID = nullptr;
3145 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3146 OMPPrivateScope PrivateScope(CGF);
3147 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3148 CGF.EmitOMPPrivateClause(S, PrivateScope);
3149 (void)PrivateScope.Privatize();
3150
3151 Action.Enter(CGF);
3152 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3153 };
3154 // Emit target region as a standalone region.
3155 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3156 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3157 return std::make_pair(OutlinedFn, OutlinedFnID);
3158}
3159
Samuel Antaobed3c462015-10-02 16:14:20 +00003160void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003161 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3162
3163 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003164 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003165
Samuel Antaoee8fb302016-01-06 13:42:12 +00003166 llvm::Function *Fn = nullptr;
3167 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003168
3169 // Check if we have any if clause associated with the directive.
3170 const Expr *IfCond = nullptr;
3171
3172 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3173 IfCond = C->getCondition();
3174 }
3175
3176 // Check if we have any device clause associated with the directive.
3177 const Expr *Device = nullptr;
3178 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3179 Device = C->getDevice();
3180 }
3181
Samuel Antaoee8fb302016-01-06 13:42:12 +00003182 // Check if we have an if clause whose conditional always evaluates to false
3183 // or if we do not have any targets specified. If so the target region is not
3184 // an offload entry point.
3185 bool IsOffloadEntry = true;
3186 if (IfCond) {
3187 bool Val;
3188 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3189 IsOffloadEntry = false;
3190 }
3191 if (CGM.getLangOpts().OMPTargetTriples.empty())
3192 IsOffloadEntry = false;
3193
3194 assert(CurFuncDecl && "No parent declaration for target region!");
3195 StringRef ParentName;
3196 // In case we have Ctors/Dtors we use the complete type variant to produce
3197 // the mangling of the device outlined kernel.
3198 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3199 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3200 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3201 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3202 else
3203 ParentName =
3204 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3205
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003206 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3207 CGM, S, ParentName, IsOffloadEntry);
3208 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003209 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003210 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003211}
3212
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003213static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3214 const OMPExecutableDirective &S,
3215 OpenMPDirectiveKind InnermostKind,
3216 const RegionCodeGenTy &CodeGen) {
3217 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003218 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3219 emitParallelOrTeamsOutlinedFunction(S,
3220 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003221
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003222 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3223 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3224 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3225 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003226 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3227 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003228
Carlo Bertollic6872252016-04-04 15:55:02 +00003229 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3230 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003231 }
3232
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003233 OMPLexicalScope Scope(CGF, S);
3234 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3235 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003236 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3237 CapturedVars);
3238}
3239
3240void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003241 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003242 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003243 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003244 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3245 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003246 (void)PrivateScope.Privatize();
3247 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3248 };
3249 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003250}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003251
3252void CodeGenFunction::EmitOMPCancellationPointDirective(
3253 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003254 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3255 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003256}
3257
Alexey Bataev80909872015-07-02 11:25:17 +00003258void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003259 const Expr *IfCond = nullptr;
3260 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3261 if (C->getNameModifier() == OMPD_unknown ||
3262 C->getNameModifier() == OMPD_cancel) {
3263 IfCond = C->getCondition();
3264 break;
3265 }
3266 }
3267 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003268 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003269}
3270
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003271CodeGenFunction::JumpDest
3272CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3273 if (Kind == OMPD_parallel || Kind == OMPD_task)
3274 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003275 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003276 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003277 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003278}
Michael Wong65f367f2015-07-21 13:44:28 +00003279
3280// Generate the instructions for '#pragma omp target data' directive.
3281void CodeGenFunction::EmitOMPTargetDataDirective(
3282 const OMPTargetDataDirective &S) {
Samuel Antaodf158d52016-04-27 22:58:19 +00003283 // The target data enclosed region is implemented just by emitting the
3284 // statement.
3285 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3286 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3287 };
3288
3289 // If we don't have target devices, don't bother emitting the data mapping
3290 // code.
3291 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
3292 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3293
3294 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_data,
3295 CodeGen);
3296 return;
3297 }
3298
3299 // Check if we have any if clause associated with the directive.
3300 const Expr *IfCond = nullptr;
3301 if (auto *C = S.getSingleClause<OMPIfClause>())
3302 IfCond = C->getCondition();
3303
3304 // Check if we have any device clause associated with the directive.
3305 const Expr *Device = nullptr;
3306 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3307 Device = C->getDevice();
3308
3309 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, CodeGen);
Michael Wong65f367f2015-07-21 13:44:28 +00003310}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003311
Samuel Antaodf67fc42016-01-19 19:15:56 +00003312void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3313 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003314 // If we don't have target devices, don't bother emitting the data mapping
3315 // code.
3316 if (CGM.getLangOpts().OMPTargetTriples.empty())
3317 return;
3318
3319 // Check if we have any if clause associated with the directive.
3320 const Expr *IfCond = nullptr;
3321 if (auto *C = S.getSingleClause<OMPIfClause>())
3322 IfCond = C->getCondition();
3323
3324 // Check if we have any device clause associated with the directive.
3325 const Expr *Device = nullptr;
3326 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3327 Device = C->getDevice();
3328
Samuel Antao8dd66282016-04-27 23:14:30 +00003329 CGM.getOpenMPRuntime().emitTargetEnterOrExitDataCall(*this, S, IfCond,
3330 Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003331}
3332
Samuel Antao72590762016-01-19 20:04:50 +00003333void CodeGenFunction::EmitOMPTargetExitDataDirective(
3334 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003335 // If we don't have target devices, don't bother emitting the data mapping
3336 // code.
3337 if (CGM.getLangOpts().OMPTargetTriples.empty())
3338 return;
3339
3340 // Check if we have any if clause associated with the directive.
3341 const Expr *IfCond = nullptr;
3342 if (auto *C = S.getSingleClause<OMPIfClause>())
3343 IfCond = C->getCondition();
3344
3345 // Check if we have any device clause associated with the directive.
3346 const Expr *Device = nullptr;
3347 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3348 Device = C->getDevice();
3349
3350 CGM.getOpenMPRuntime().emitTargetEnterOrExitDataCall(*this, S, IfCond,
3351 Device);
Samuel Antao72590762016-01-19 20:04:50 +00003352}
3353
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003354void CodeGenFunction::EmitOMPTargetParallelDirective(
3355 const OMPTargetParallelDirective &S) {
3356 // TODO: codegen for target parallel.
3357}
3358
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003359void CodeGenFunction::EmitOMPTargetParallelForDirective(
3360 const OMPTargetParallelForDirective &S) {
3361 // TODO: codegen for target parallel for.
3362}
3363
Alexey Bataev7292c292016-04-25 12:22:29 +00003364/// Emit a helper variable and return corresponding lvalue.
3365static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3366 const ImplicitParamDecl *PVD,
3367 CodeGenFunction::OMPPrivateScope &Privates) {
3368 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3369 Privates.addPrivate(
3370 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3371}
3372
3373void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3374 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3375 // Emit outlined function for task construct.
3376 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3377 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3378 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3379 const Expr *IfCond = nullptr;
3380 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3381 if (C->getNameModifier() == OMPD_unknown ||
3382 C->getNameModifier() == OMPD_taskloop) {
3383 IfCond = C->getCondition();
3384 break;
3385 }
3386 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003387
3388 OMPTaskDataTy Data;
3389 // Check if taskloop must be emitted without taskgroup.
3390 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003391 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003392 Data.Tied = true;
3393 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003394 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3395 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003396 Data.Schedule.setInt(/*IntVal=*/false);
3397 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003398 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3399 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003400 Data.Schedule.setInt(/*IntVal=*/true);
3401 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003402 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003403
3404 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3405 // if (PreCond) {
3406 // for (IV in 0..LastIteration) BODY;
3407 // <Final counter/linear vars updates>;
3408 // }
3409 //
3410
3411 // Emit: if (PreCond) - begin.
3412 // If the condition constant folds and can be elided, avoid emitting the
3413 // whole loop.
3414 bool CondConstant;
3415 llvm::BasicBlock *ContBlock = nullptr;
3416 OMPLoopScope PreInitScope(CGF, S);
3417 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3418 if (!CondConstant)
3419 return;
3420 } else {
3421 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3422 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3423 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3424 CGF.getProfileCount(&S));
3425 CGF.EmitBlock(ThenBlock);
3426 CGF.incrementProfileCounter(&S);
3427 }
3428
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003429 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3430 CGF.EmitOMPSimdInit(S);
3431
Alexey Bataev7292c292016-04-25 12:22:29 +00003432 OMPPrivateScope LoopScope(CGF);
3433 // Emit helper vars inits.
3434 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3435 auto *I = CS->getCapturedDecl()->param_begin();
3436 auto *LBP = std::next(I, LowerBound);
3437 auto *UBP = std::next(I, UpperBound);
3438 auto *STP = std::next(I, Stride);
3439 auto *LIP = std::next(I, LastIter);
3440 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3441 LoopScope);
3442 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3443 LoopScope);
3444 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3445 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3446 LoopScope);
3447 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003448 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003449 (void)LoopScope.Privatize();
3450 // Emit the loop iteration variable.
3451 const Expr *IVExpr = S.getIterationVariable();
3452 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3453 CGF.EmitVarDecl(*IVDecl);
3454 CGF.EmitIgnoredExpr(S.getInit());
3455
3456 // Emit the iterations count variable.
3457 // If it is not a variable, Sema decided to calculate iterations count on
3458 // each iteration (e.g., it is foldable into a constant).
3459 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3460 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3461 // Emit calculation of the iterations count.
3462 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3463 }
3464
3465 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3466 S.getInc(),
3467 [&S](CodeGenFunction &CGF) {
3468 CGF.EmitOMPLoopBody(S, JumpDest());
3469 CGF.EmitStopPoint(&S);
3470 },
3471 [](CodeGenFunction &) {});
3472 // Emit: if (PreCond) - end.
3473 if (ContBlock) {
3474 CGF.EmitBranch(ContBlock);
3475 CGF.EmitBlock(ContBlock, true);
3476 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003477 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3478 if (HasLastprivateClause) {
3479 CGF.EmitOMPLastprivateClauseFinal(
3480 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3481 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3482 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3483 (*LIP)->getType(), S.getLocStart())));
3484 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003485 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003486 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3487 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3488 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003489 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3490 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003491 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
3492 OutlinedFn, SharedsTy,
3493 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003494 };
3495 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
3496 CodeGen);
3497 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003498 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003499}
3500
Alexey Bataev49f6e782015-12-01 04:18:41 +00003501void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003502 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003503}
3504
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003505void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3506 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003507 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003508}