blob: 1ca04a6a578783e9562d5df011b97b29cff802ba [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev9959db52014-05-06 10:08:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit OpenMP nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Alexey Bataev3392d762016-02-16 11:18:12 +000013#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000014#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021using namespace clang;
22using namespace CodeGen;
23
Alexey Bataev3392d762016-02-16 11:18:12 +000024namespace {
25/// Lexical scope for OpenMP executable constructs, that handles correct codegen
26/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000027class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000028 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
29 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000030 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
31 if (const auto *PreInit =
32 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000033 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000034 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000035 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000036 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000037 CodeGenFunction::AutoVarEmission Emission =
38 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
39 CGF.EmitAutoVarCleanups(Emission);
40 }
41 }
Alexey Bataev3392d762016-02-16 11:18:12 +000042 }
43 }
44 }
45 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000046 CodeGenFunction::OMPPrivateScope InlinedShareds;
47
48 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
49 return CGF.LambdaCaptureFields.lookup(VD) ||
50 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
51 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
52 }
Alexey Bataev3392d762016-02-16 11:18:12 +000053
Alexey Bataev3392d762016-02-16 11:18:12 +000054public:
Alexey Bataev475a7442018-01-12 19:39:11 +000055 OMPLexicalScope(
56 CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
58 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000059 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
60 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000061 if (EmitPreInitStmt)
62 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000063 if (!CapturedRegion.hasValue())
64 return;
65 assert(S.hasAssociatedStmt() &&
66 "Expected associated statement for inlined directive.");
67 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000068 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000069 if (C.capturesVariable() || C.capturesVariableByCopy()) {
70 auto *VD = C.getCapturedVar();
71 assert(VD == VD->getCanonicalDecl() &&
72 "Canonical decl must be captured.");
73 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000074 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000075 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
76 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000077 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000078 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
79 return CGF.EmitLValue(&DRE).getAddress();
80 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000081 }
82 }
Alexey Bataev475a7442018-01-12 19:39:11 +000083 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +000099 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
100 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000101};
102
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000103/// Lexical scope for OpenMP teams construct, that handles correct codegen
104/// for captured expressions.
105class OMPTeamsScope final : public OMPLexicalScope {
106 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
107 OpenMPDirectiveKind Kind = S.getDirectiveKind();
108 return !isOpenMPTargetExecutionDirective(Kind) &&
109 isOpenMPTeamsDirective(Kind);
110 }
111
112public:
113 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000114 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
115 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000122 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevf71939c2019-09-18 19:24:07 +0000123 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000124 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf71939c2019-09-18 19:24:07 +0000126 EmittedAsPrivate.insert(VD->getCanonicalDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000127 (void)PreCondVars.setVarAddr(
128 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000129 }
Alexey Bataevf71939c2019-09-18 19:24:07 +0000130 // Mark private vars as undefs.
131 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
132 for (const Expr *IRef : C->varlists()) {
133 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
134 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
135 (void)PreCondVars.setVarAddr(
136 CGF, OrigVD,
137 Address(llvm::UndefValue::get(
138 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
139 OrigVD->getType().getNonReferenceType()))),
140 CGF.getContext().getDeclAlign(OrigVD)));
141 }
142 }
143 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000144 (void)PreCondVars.apply(CGF);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000145 // Emit init, __range and __end variables for C++ range loops.
146 const Stmt *Body =
147 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
148 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
149 Body = Body->IgnoreContainers();
150 if (auto *For = dyn_cast<ForStmt>(Body)) {
151 Body = For->getBody();
152 } else {
153 assert(isa<CXXForRangeStmt>(Body) &&
Alexey Bataevd457f7e2019-10-07 19:57:40 +0000154 "Expected canonical for loop or range-based for loop.");
Alexey Bataevbef93a92019-10-07 18:54:57 +0000155 auto *CXXFor = cast<CXXForRangeStmt>(Body);
156 if (const Stmt *Init = CXXFor->getInit())
157 CGF.EmitStmt(Init);
158 CGF.EmitStmt(CXXFor->getRangeStmt());
159 CGF.EmitStmt(CXXFor->getEndStmt());
160 Body = CXXFor->getBody();
161 }
162 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000163 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000164 for (const auto *I : PreInits->decls())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000166 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000167 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000168 }
169
170public:
171 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
172 : CodeGenFunction::RunCleanupsScope(CGF) {
173 emitPreInitStmt(CGF, S);
174 }
175};
176
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000177class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
178 CodeGenFunction::OMPPrivateScope InlinedShareds;
179
180 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
181 return CGF.LambdaCaptureFields.lookup(VD) ||
182 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
183 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
184 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
185 }
186
187public:
188 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
189 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
190 InlinedShareds(CGF) {
191 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000192 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
193 if (const auto *PreInit =
194 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000195 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000196 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000197 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000198 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000199 CodeGenFunction::AutoVarEmission Emission =
200 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
201 CGF.EmitAutoVarCleanups(Emission);
202 }
203 }
204 }
205 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
206 for (const Expr *E : UDP->varlists()) {
207 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
208 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
209 CGF.EmitVarDecl(*OED);
210 }
211 }
212 }
213 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
214 CGF.EmitOMPPrivateClause(S, InlinedShareds);
215 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
216 if (const Expr *E = TG->getReductionRef())
217 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
218 }
219 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
220 while (CS) {
221 for (auto &C : CS->captures()) {
222 if (C.capturesVariable() || C.capturesVariableByCopy()) {
223 auto *VD = C.getCapturedVar();
224 assert(VD == VD->getCanonicalDecl() &&
225 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000226 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000227 isCapturedVar(CGF, VD) ||
228 (CGF.CapturedStmtInfo &&
229 InlinedShareds.isGlobalVarCaptured(VD)),
230 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000231 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000232 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
233 return CGF.EmitLValue(&DRE).getAddress();
234 });
235 }
236 }
237 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
238 }
239 (void)InlinedShareds.Privatize();
240 }
241};
242
Alexey Bataev3392d762016-02-16 11:18:12 +0000243} // namespace
244
Alexey Bataevf8365372017-11-17 17:57:25 +0000245static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
246 const OMPExecutableDirective &S,
247 const RegionCodeGenTy &CodeGen);
248
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000249LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000250 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
251 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000252 OrigVD = OrigVD->getCanonicalDecl();
253 bool IsCaptured =
254 LambdaCaptureFields.lookup(OrigVD) ||
255 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
256 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000257 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000258 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
259 return EmitLValue(&DRE);
260 }
261 }
262 return EmitLValue(E);
263}
264
Alexey Bataev1189bd02016-01-26 12:20:39 +0000265llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000266 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000267 llvm::Value *Size = nullptr;
268 auto SizeInChars = C.getTypeSizeInChars(Ty);
269 if (SizeInChars.isZero()) {
270 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000271 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
272 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000273 Ty = VlaSize.Type;
274 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
275 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000276 }
277 SizeInChars = C.getTypeSizeInChars(Ty);
278 if (SizeInChars.isZero())
279 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000280 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
281 }
282 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000283}
284
Alexey Bataev2377fe92015-09-10 08:12:02 +0000285void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000286 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000287 const RecordDecl *RD = S.getCapturedRecordDecl();
288 auto CurField = RD->field_begin();
289 auto CurCap = S.captures().begin();
290 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
291 E = S.capture_init_end();
292 I != E; ++I, ++CurField, ++CurCap) {
293 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000294 const VariableArrayType *VAT = CurField->getCapturedVLAType();
295 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000296 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000297 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000298 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000299 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000300 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000301
302 // If the field is not a pointer, we need to save the actual value
303 // and load it as a void pointer.
304 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000305 ASTContext &Ctx = getContext();
306 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000307 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000308 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000309 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
310
Alexey Bataevddf3db92018-04-13 17:31:06 +0000311 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000312 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000313 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000314 LValue SrcLV =
315 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
316
317 // Store the value using the source type pointer.
318 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
319
320 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000321 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000322 }
323 CapturedVars.push_back(CV);
324 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000325 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000326 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000327 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000328 }
329}
330
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000331static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
332 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000333 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000334 ASTContext &Ctx = CGF.getContext();
335
Alexey Bataevddf3db92018-04-13 17:31:06 +0000336 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
337 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
338 Ctx.getPointerType(DstType), Loc);
339 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000340 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
341 .getAddress();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000342 return TmpAddr;
343}
344
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000345static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000346 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000347 return C.getLValueReferenceType(
348 getCanonicalParamType(C, T.getNonReferenceType()),
349 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000350 if (T->isPointerType())
351 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000352 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
353 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000354 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000355 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000356 return C.getCanonicalType(T);
357 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000358 return C.getCanonicalParamType(T);
359}
360
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000361namespace {
362 /// Contains required data for proper outlined function codegen.
363 struct FunctionOptions {
364 /// Captured statement for which the function is generated.
365 const CapturedStmt *S = nullptr;
366 /// true if cast to/from UIntPtr is required for variables captured by
367 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000368 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000369 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000371 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000373 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
375 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000376 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000377 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
378 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000379 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000380 };
381}
382
Alexey Bataeve754b182017-08-09 19:38:53 +0000383static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000384 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000385 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 &LocalAddrs,
387 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
388 &VLASizes,
389 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
390 const CapturedDecl *CD = FO.S->getCapturedDecl();
391 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000392 assert(CD->hasBody() && "missing CapturedDecl body");
393
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000394 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000396 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000398 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000399 Args.append(CD->param_begin(),
400 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000401 TargetArgs.append(
402 CD->param_begin(),
403 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000404 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000405 FunctionDecl *DebugFunctionDecl = nullptr;
406 if (!FO.UIntPtrCastRequired) {
407 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000408 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000409 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000410 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000411 SourceLocation(), DeclarationName(), FunctionTy,
412 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
413 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000414 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000415 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 QualType ArgType = FD->getType();
417 IdentifierInfo *II = nullptr;
418 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000419
420 // If this is a capture by copy and the type is not a pointer, the outlined
421 // function argument type should be uintptr and the value properly casted to
422 // uintptr. This is necessary given that the runtime library is only able to
423 // deal with pointers. We can pass in the same way the VLA type sizes to the
424 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000425 if (FO.UIntPtrCastRequired &&
426 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
427 I->capturesVariableArrayType()))
428 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000429
430 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000431 CapVar = I->getCapturedVar();
432 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000433 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000434 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000435 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000436 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000437 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000438 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000439 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000440 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000441 VarDecl *Arg;
442 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
443 Arg = ParmVarDecl::Create(
444 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000445 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000446 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
447 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
448 } else {
449 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
450 II, ArgType, ImplicitParamDecl::Other);
451 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 Args.emplace_back(Arg);
453 // Do not cast arguments if we emit function with non-original types.
454 TargetArgs.emplace_back(
455 FO.UIntPtrCastRequired
456 ? Arg
457 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458 ++I;
459 }
460 Args.append(
461 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
462 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000463 TargetArgs.append(
464 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
465 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000466
467 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000468 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000469 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000470 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
471
Alexey Bataevddf3db92018-04-13 17:31:06 +0000472 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000473 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
474 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000475 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
476 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000477 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000478 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000479
480 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000481 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000482 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000483 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000484 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000485 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000486 // Do not map arguments if we emit function with non-original types.
487 Address LocalAddr(Address::invalid());
488 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
489 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
490 TargetArgs[Cnt]);
491 } else {
492 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
493 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000494 // If we are capturing a pointer by copy we don't need to do anything, just
495 // use the value that we get from the arguments.
496 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000497 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 if (!FO.RegisterCastedArgsOnly)
499 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000500 ++Cnt;
501 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000502 continue;
503 }
504
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000505 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
506 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000508 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000509 ArgLVal = CGF.MakeAddrLValue(
510 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
511 Args[Cnt]->getName(), ArgLVal),
512 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000513 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000514 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
515 const VariableArrayType *VAT = FD->getCapturedVLAType();
516 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000518 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 QualType VarTy = Var->getType();
520 Address ArgAddr = ArgLVal.getAddress();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000521 if (ArgLVal.getType()->isLValueReferenceType()) {
522 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
523 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
524 assert(ArgLVal.getType()->isPointerType());
525 ArgAddr = CGF.EmitLoadOfPointer(
526 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000527 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000528 if (!FO.RegisterCastedArgsOnly) {
529 LocalAddrs.insert(
530 {Args[Cnt],
531 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
532 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000533 } else if (I->capturesVariableByCopy()) {
534 assert(!FD->getType()->isAnyPointerType() &&
535 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000536 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000537 LocalAddrs.insert({Args[Cnt],
538 {Var, FO.UIntPtrCastRequired
539 ? castValueFromUintptr(
540 CGF, I->getLocation(), FD->getType(),
541 Args[Cnt]->getName(), ArgLVal)
542 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 } else {
544 // If 'this' is captured, load it into CXXThisValue.
545 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000546 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000547 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000548 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000549 ++Cnt;
550 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000551 }
552
Alexey Bataeve754b182017-08-09 19:38:53 +0000553 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000554}
555
556llvm::Function *
557CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
558 assert(
559 CapturedStmtInfo &&
560 "CapturedStmtInfo should be set when generating the captured function");
561 const CapturedDecl *CD = S.getCapturedDecl();
562 // Build the argument list.
563 bool NeedWrapperFunction =
564 getDebugInfo() &&
565 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
566 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000567 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000568 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000569 SmallString<256> Buffer;
570 llvm::raw_svector_ostream Out(Buffer);
571 Out << CapturedStmtInfo->getHelperName();
572 if (NeedWrapperFunction)
573 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000574 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000575 Out.str());
576 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
577 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000578 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000579 for (const auto &LocalAddrPair : LocalAddrs) {
580 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000581 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
582 return LocalAddrPair.second.second;
583 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000584 }
585 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000586 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000587 for (const auto &VLASizePair : VLASizes)
588 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000589 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000590 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000591 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000592 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000593 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000594 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000595
Alexey Bataevefd884d2017-08-04 21:26:25 +0000596 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000597 /*RegisterCastedArgsOnly=*/true,
598 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000599 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000600 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000601 Args.clear();
602 LocalAddrs.clear();
603 VLASizes.clear();
604 llvm::Function *WrapperF =
605 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000606 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000607 llvm::SmallVector<llvm::Value *, 4> CallArgs;
608 for (const auto *Arg : Args) {
609 llvm::Value *CallArg;
610 auto I = LocalAddrs.find(Arg);
611 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000612 LValue LV = WrapperCGF.MakeAddrLValue(
613 I->second.second,
614 I->second.first ? I->second.first->getType() : Arg->getType(),
615 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000616 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 } else {
618 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000619 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000621 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000622 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000623 Arg->getType(),
624 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000625 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000626 }
627 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000628 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000629 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000630 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000631 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000632 WrapperCGF.FinishFunction();
633 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000634}
635
Alexey Bataev9959db52014-05-06 10:08:46 +0000636//===----------------------------------------------------------------------===//
637// OpenMP Directive Emission
638//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000639void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000640 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000641 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 // Perform element-by-element initialization.
643 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000644
645 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000646 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
647 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000648 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
649
Alexey Bataevddf3db92018-04-13 17:31:06 +0000650 llvm::Value *SrcBegin = SrcAddr.getPointer();
651 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000652 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000653 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000654 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000655 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
656 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
657 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000658 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
659 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000660
Alexey Bataev420d45b2015-04-14 05:11:24 +0000661 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000662 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000663 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000664
665 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
666
667 llvm::PHINode *SrcElementPHI =
668 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
669 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
670 Address SrcElementCurrent =
671 Address(SrcElementPHI,
672 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
673
674 llvm::PHINode *DestElementPHI =
675 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
676 DestElementPHI->addIncoming(DestBegin, EntryBB);
677 Address DestElementCurrent =
678 Address(DestElementPHI,
679 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000680
Alexey Bataev420d45b2015-04-14 05:11:24 +0000681 // Emit copy.
682 CopyGen(DestElementCurrent, SrcElementCurrent);
683
684 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000685 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000686 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000687 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000688 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000689 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000690 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
692 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000693 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
694 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000695
696 // Done.
697 EmitBlock(DoneBB, /*IsFinished=*/true);
698}
699
John McCall7f416cc2015-09-08 08:05:57 +0000700void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
701 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 const VarDecl *SrcVD, const Expr *Copy) {
703 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000704 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 if (BO && BO->getOpcode() == BO_Assign) {
706 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000707 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
708 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
709 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 } else {
711 // For arrays with complex element types perform element by element
712 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000713 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000715 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 // Working with the single array element, so have to remap
717 // destination and source variables to corresponding array
718 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000719 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000720 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
721 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000723 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000724 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000726 } else {
727 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000728 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000729 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
730 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000731 (void)Remap.Privatize();
732 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000733 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000734 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000735}
736
Alexey Bataev69c62a92015-04-15 04:52:20 +0000737bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
738 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000739 if (!HaveInsertPoint())
740 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000741 bool DeviceConstTarget =
742 getLangOpts().OpenMPIsDevice &&
743 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000744 bool FirstprivateIsLastprivate = false;
745 llvm::DenseSet<const VarDecl *> Lastprivates;
746 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
747 for (const auto *D : C->varlists())
748 Lastprivates.insert(
749 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
750 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000751 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000752 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
753 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
754 // Force emission of the firstprivate copy if the directive does not emit
755 // outlined function, like omp for, omp simd, omp distribute etc.
756 bool MustEmitFirstprivateCopy =
757 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000758 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000759 auto IRef = C->varlist_begin();
760 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000761 for (const Expr *IInit : C->private_copies()) {
762 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000763 bool ThisFirstprivateIsLastprivate =
764 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000765 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000766 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000767 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000768 !FD->getType()->isReferenceType() &&
769 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000770 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
771 ++IRef;
772 ++InitsRef;
773 continue;
774 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000775 // Do not emit copy for firstprivate constant variables in target regions,
776 // captured by reference.
777 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000778 FD && FD->getType()->isReferenceType() &&
779 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000780 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
781 OrigVD);
782 ++IRef;
783 ++InitsRef;
784 continue;
785 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000786 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000787 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000788 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000789 const auto *VDInit =
790 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000791 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000792 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
794 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataeve0ef04f2019-05-23 22:30:43 +0000795 LValue OriginalLVal;
796 if (!FD) {
797 // Check if the firstprivate variable is just a constant value.
798 ConstantEmission CE = tryEmitAsConstant(&DRE);
799 if (CE && !CE.isReference()) {
800 // Constant value, no need to create a copy.
801 ++IRef;
802 ++InitsRef;
803 continue;
804 }
805 if (CE && CE.isReference()) {
806 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
807 } else {
808 assert(!CE && "Expected non-constant firstprivate.");
809 OriginalLVal = EmitLValue(&DRE);
810 }
811 } else {
812 OriginalLVal = EmitLValue(&DRE);
813 }
Alexey Bataevfeddd642016-04-22 09:05:03 +0000814 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000815 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000816 // Emit VarDecl with copy init for arrays.
817 // Get the address of the original variable captured in current
818 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000819 IsRegistered = PrivateScope.addPrivate(
820 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
821 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
822 const Expr *Init = VD->getInit();
823 if (!isa<CXXConstructExpr>(Init) ||
824 isTrivialInitializer(Init)) {
825 // Perform simple memcpy.
826 LValue Dest =
827 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
828 EmitAggregateAssign(Dest, OriginalLVal, Type);
829 } else {
830 EmitOMPAggregateAssign(
831 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
832 Type,
833 [this, VDInit, Init](Address DestElement,
834 Address SrcElement) {
835 // Clean up any temporaries needed by the
836 // initialization.
837 RunCleanupsScope InitScope(*this);
838 // Emit initialization for single element.
839 setAddrOfLocalVar(VDInit, SrcElement);
840 EmitAnyExprToMem(Init, DestElement,
841 Init->getType().getQualifiers(),
842 /*IsInitializer*/ false);
843 LocalDeclMap.erase(VDInit);
844 });
845 }
846 EmitAutoVarCleanups(Emission);
847 return Emission.getAllocatedAddress();
848 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000849 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000850 Address OriginalAddr = OriginalLVal.getAddress();
851 IsRegistered = PrivateScope.addPrivate(
852 OrigVD, [this, VDInit, OriginalAddr, VD]() {
853 // Emit private VarDecl with copy init.
854 // Remap temp VDInit variable to the address of the original
855 // variable (for proper handling of captured global variables).
856 setAddrOfLocalVar(VDInit, OriginalAddr);
857 EmitDecl(*VD);
858 LocalDeclMap.erase(VDInit);
859 return GetAddrOfLocalVar(VD);
860 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000861 }
862 assert(IsRegistered &&
863 "firstprivate var already registered as private");
864 // Silence the warning about unused variable.
865 (void)IsRegistered;
866 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000867 ++IRef;
868 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000869 }
870 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000871 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000872}
873
Alexey Bataev03b340a2014-10-21 03:16:40 +0000874void CodeGenFunction::EmitOMPPrivateClause(
875 const OMPExecutableDirective &D,
876 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000877 if (!HaveInsertPoint())
878 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000879 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000880 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000881 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000882 for (const Expr *IInit : C->private_copies()) {
883 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000884 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000885 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
886 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
887 // Emit private VarDecl with copy init.
888 EmitDecl(*VD);
889 return GetAddrOfLocalVar(VD);
890 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000891 assert(IsRegistered && "private var already registered as private");
892 // Silence the warning about unused variable.
893 (void)IsRegistered;
894 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000895 ++IRef;
896 }
897 }
898}
899
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000900bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000901 if (!HaveInsertPoint())
902 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000903 // threadprivate_var1 = master_threadprivate_var1;
904 // operator=(threadprivate_var2, master_threadprivate_var2);
905 // ...
906 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000907 llvm::DenseSet<const VarDecl *> CopiedVars;
908 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000909 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000910 auto IRef = C->varlist_begin();
911 auto ISrcRef = C->source_exprs().begin();
912 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000913 for (const Expr *AssignOp : C->assignment_ops()) {
914 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000915 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000916 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000917 // Get the address of the master variable. If we are emitting code with
918 // TLS support, the address is passed from the master as field in the
919 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000920 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000921 if (getLangOpts().OpenMPUseTLS &&
922 getContext().getTargetInfo().isTLSSupported()) {
923 assert(CapturedStmtInfo->lookup(VD) &&
924 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000925 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
926 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000927 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000928 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000929 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000930 MasterAddr =
931 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
932 : CGM.GetAddrOfGlobal(VD),
933 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000934 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000935 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000936 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000937 if (CopiedVars.size() == 1) {
938 // At first check if current thread is a master thread. If it is, no
939 // need to copy data.
940 CopyBegin = createBasicBlock("copyin.not.master");
941 CopyEnd = createBasicBlock("copyin.not.master.end");
942 Builder.CreateCondBr(
943 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000944 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000945 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
946 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000947 CopyBegin, CopyEnd);
948 EmitBlock(CopyBegin);
949 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000950 const auto *SrcVD =
951 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
952 const auto *DestVD =
953 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000954 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000955 }
956 ++IRef;
957 ++ISrcRef;
958 ++IDestRef;
959 }
960 }
961 if (CopyEnd) {
962 // Exit out of copying procedure for non-master thread.
963 EmitBlock(CopyEnd, /*IsFinished=*/true);
964 return true;
965 }
966 return false;
967}
968
Alexey Bataev38e89532015-04-16 04:54:05 +0000969bool CodeGenFunction::EmitOMPLastprivateClauseInit(
970 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000971 if (!HaveInsertPoint())
972 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000974 llvm::DenseSet<const VarDecl *> SIMDLCVs;
975 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000976 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
977 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000978 SIMDLCVs.insert(
979 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
980 }
981 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000982 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000983 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000984 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000985 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
986 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000987 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000988 auto IRef = C->varlist_begin();
989 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000990 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000991 // Keep the address of the original variable for future update at the end
992 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000993 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000994 // Taskloops do not require additional initialization, it is done in
995 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000996 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000997 const auto *DestVD =
998 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
999 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001000 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1001 /*RefersToEnclosingVariableOrCapture=*/
1002 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1003 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00001004 return EmitLValue(&DRE).getAddress();
1005 });
1006 // Check if the variable is also a firstprivate: in this case IInit is
1007 // not generated. Initialization of this variable will happen in codegen
1008 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001009 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001010 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1011 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +00001012 // Emit private VarDecl with copy init.
1013 EmitDecl(*VD);
1014 return GetAddrOfLocalVar(VD);
1015 });
Alexey Bataevd130fd12015-05-13 10:23:02 +00001016 assert(IsRegistered &&
1017 "lastprivate var already registered as private");
1018 (void)IsRegistered;
1019 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001020 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001021 ++IRef;
1022 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001023 }
1024 }
1025 return HasAtLeastOneLastprivate;
1026}
1027
1028void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001029 const OMPExecutableDirective &D, bool NoFinals,
1030 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001031 if (!HaveInsertPoint())
1032 return;
Alexey Bataev38e89532015-04-16 04:54:05 +00001033 // Emit following code:
1034 // if (<IsLastIterCond>) {
1035 // orig_var1 = private_orig_var1;
1036 // ...
1037 // orig_varn = private_orig_varn;
1038 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001039 llvm::BasicBlock *ThenBB = nullptr;
1040 llvm::BasicBlock *DoneBB = nullptr;
1041 if (IsLastIterCond) {
1042 ThenBB = createBasicBlock(".omp.lastprivate.then");
1043 DoneBB = createBasicBlock(".omp.lastprivate.done");
1044 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1045 EmitBlock(ThenBB);
1046 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001047 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1048 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001049 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001050 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001051 for (const Expr *F : LoopDirective->finals()) {
1052 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001053 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1054 if (NoFinals)
1055 AlreadyEmittedVars.insert(D);
1056 else
1057 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001058 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001059 }
1060 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001061 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1062 auto IRef = C->varlist_begin();
1063 auto ISrcRef = C->source_exprs().begin();
1064 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001065 for (const Expr *AssignOp : C->assignment_ops()) {
1066 const auto *PrivateVD =
1067 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001068 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001069 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001070 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1071 // If lastprivate variable is a loop control variable for loop-based
1072 // directive, update its value before copyin back to original
1073 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001074 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001075 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001076 const auto *SrcVD =
1077 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1078 const auto *DestVD =
1079 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001080 // Get the address of the original variable.
1081 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1082 // Get the address of the private variable.
1083 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001084 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001085 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001086 Address(Builder.CreateLoad(PrivateAddr),
1087 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001088 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001089 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001090 ++IRef;
1091 ++ISrcRef;
1092 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001094 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001095 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001096 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001097 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001098 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001099}
1100
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001101void CodeGenFunction::EmitOMPReductionClauseInit(
1102 const OMPExecutableDirective &D,
1103 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001104 if (!HaveInsertPoint())
1105 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001106 SmallVector<const Expr *, 4> Shareds;
1107 SmallVector<const Expr *, 4> Privates;
1108 SmallVector<const Expr *, 4> ReductionOps;
1109 SmallVector<const Expr *, 4> LHSs;
1110 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001111 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001112 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001113 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 auto ILHS = C->lhs_exprs().begin();
1115 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001116 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 Shareds.emplace_back(Ref);
1118 Privates.emplace_back(*IPriv);
1119 ReductionOps.emplace_back(*IRed);
1120 LHSs.emplace_back(*ILHS);
1121 RHSs.emplace_back(*IRHS);
1122 std::advance(IPriv, 1);
1123 std::advance(IRed, 1);
1124 std::advance(ILHS, 1);
1125 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001126 }
1127 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001128 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1129 unsigned Count = 0;
1130 auto ILHS = LHSs.begin();
1131 auto IRHS = RHSs.begin();
1132 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001133 for (const Expr *IRef : Shareds) {
1134 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 // Emit private VarDecl with reduction init.
1136 RedCG.emitSharedLValue(*this, Count);
1137 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001138 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1140 RedCG.getSharedLValue(Count),
1141 [&Emission](CodeGenFunction &CGF) {
1142 CGF.EmitAutoVarInit(Emission);
1143 return true;
1144 });
1145 EmitAutoVarCleanups(Emission);
1146 Address BaseAddr = RedCG.adjustPrivateAddress(
1147 *this, Count, Emission.getAllocatedAddress());
1148 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001149 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001150 assert(IsRegistered && "private var already registered as private");
1151 // Silence the warning about unused variable.
1152 (void)IsRegistered;
1153
Alexey Bataevddf3db92018-04-13 17:31:06 +00001154 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1155 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001156 QualType Type = PrivateVD->getType();
1157 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1158 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001159 // Store the address of the original variable associated with the LHS
1160 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001161 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001162 return RedCG.getSharedLValue(Count).getAddress();
1163 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001164 PrivateScope.addPrivate(
1165 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001166 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1167 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001168 // Store the address of the original variable associated with the LHS
1169 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001170 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001171 return RedCG.getSharedLValue(Count).getAddress();
1172 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001173 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001174 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1175 ConvertTypeForMem(RHSVD->getType()),
1176 "rhs.begin");
1177 });
1178 } else {
1179 QualType Type = PrivateVD->getType();
1180 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1181 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1182 // Store the address of the original variable associated with the LHS
1183 // implicit variable.
1184 if (IsArray) {
1185 OriginalAddr = Builder.CreateElementBitCast(
1186 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1187 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001188 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001189 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001190 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001191 return IsArray
1192 ? Builder.CreateElementBitCast(
1193 GetAddrOfLocalVar(PrivateVD),
1194 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1195 : GetAddrOfLocalVar(PrivateVD);
1196 });
1197 }
1198 ++ILHS;
1199 ++IRHS;
1200 ++IPriv;
1201 ++Count;
1202 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001203}
1204
1205void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001206 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001207 if (!HaveInsertPoint())
1208 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001209 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001210 llvm::SmallVector<const Expr *, 8> LHSExprs;
1211 llvm::SmallVector<const Expr *, 8> RHSExprs;
1212 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001213 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001214 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001215 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001216 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001217 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1218 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1219 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1220 }
1221 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001222 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1223 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001224 ReductionKind == OMPD_simd;
1225 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001226 // Emit nowait reduction if nowait clause is present or directive is a
1227 // parallel directive (it always has implicit barrier).
1228 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001229 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001230 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001231 }
1232}
1233
Alexey Bataev61205072016-03-02 04:57:40 +00001234static void emitPostUpdateForReductionClause(
1235 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001236 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001237 if (!CGF.HaveInsertPoint())
1238 return;
1239 llvm::BasicBlock *DoneBB = nullptr;
1240 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001241 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001242 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001243 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001244 // If the first post-update expression is found, emit conditional
1245 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001246 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001247 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1248 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1249 CGF.EmitBlock(ThenBB);
1250 }
1251 }
1252 CGF.EmitIgnoredExpr(PostUpdate);
1253 }
1254 }
1255 if (DoneBB)
1256 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1257}
1258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001259namespace {
1260/// Codegen lambda for appending distribute lower and upper bounds to outlined
1261/// parallel function. This is necessary for combined constructs such as
1262/// 'distribute parallel for'
1263typedef llvm::function_ref<void(CodeGenFunction &,
1264 const OMPExecutableDirective &,
1265 llvm::SmallVectorImpl<llvm::Value *> &)>
1266 CodeGenBoundParametersTy;
1267} // anonymous namespace
1268
1269static void emitCommonOMPParallelDirective(
1270 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1271 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1272 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001273 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001274 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001275 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1276 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001277 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001278 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001279 llvm::Value *NumThreads =
1280 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1281 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001282 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001283 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001284 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001285 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001286 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001287 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001288 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001289 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001290 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001291 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1292 if (C->getNameModifier() == OMPD_unknown ||
1293 C->getNameModifier() == OMPD_parallel) {
1294 IfCond = C->getCondition();
1295 break;
1296 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001297 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001298
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001299 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001300 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001301 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1302 // lower and upper bounds with the pragma 'for' chunking mechanism.
1303 // The following lambda takes care of appending the lower and upper bound
1304 // parameters when necessary
1305 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001306 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001307 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001308 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001309}
1310
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001311static void emitEmptyBoundParameters(CodeGenFunction &,
1312 const OMPExecutableDirective &,
1313 llvm::SmallVectorImpl<llvm::Value *> &) {}
1314
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001317 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001318 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001319 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001320 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001321 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1322 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001323 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001324 // propagation master's thread values of threadprivate variables to local
1325 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001326 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001327 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001328 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001329 }
1330 CGF.EmitOMPPrivateClause(S, PrivateScope);
1331 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1332 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001333 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001334 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001335 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001336 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1337 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001338 emitPostUpdateForReductionClause(*this, S,
1339 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001340}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001341
Alexey Bataev0f34da12015-07-02 04:17:07 +00001342void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1343 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001344 RunCleanupsScope BodyScope(*this);
1345 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001346 for (const Expr *UE : D.updates())
1347 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001348 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001349 // In distribute directives only loop counters may be marked as linear, no
1350 // need to generate the code for them.
1351 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1352 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001353 for (const Expr *UE : C->updates())
1354 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001355 }
Alexander Musman3276a272015-03-21 10:12:56 +00001356 }
1357
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001359 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001360 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexey Bataevf8be4762019-08-14 19:30:06 +00001361 for (const Expr *E : D.finals_conditions()) {
1362 if (!E)
1363 continue;
1364 // Check that loop counter in non-rectangular nest fits into the iteration
1365 // space.
1366 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1367 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1368 getProfileCount(D.getBody()));
1369 EmitBlock(NextBB);
1370 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00001371 // Emit loop variables for C++ range loops.
1372 const Stmt *Body =
1373 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1374 for (unsigned Cnt = 0; Cnt < D.getCollapsedNumber(); ++Cnt) {
1375 Body = Body->IgnoreContainers();
1376 if (auto *For = dyn_cast<ForStmt>(Body)) {
1377 Body = For->getBody();
1378 } else {
1379 assert(isa<CXXForRangeStmt>(Body) &&
Alexey Bataevd457f7e2019-10-07 19:57:40 +00001380 "Expected canonical for loop or range-based for loop.");
Alexey Bataevbef93a92019-10-07 18:54:57 +00001381 auto *CXXFor = cast<CXXForRangeStmt>(Body);
1382 EmitStmt(CXXFor->getLoopVarStmt());
1383 Body = CXXFor->getBody();
1384 }
1385 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001386 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001387 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001388 // The end (updates/cleanups).
1389 EmitBlock(Continue.getBlock());
1390 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001391}
1392
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001393void CodeGenFunction::EmitOMPInnerLoop(
1394 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1395 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001396 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1397 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001398 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001399
1400 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001401 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001402 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001403 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001404 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1405 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001406
1407 // If there are any cleanups between here and the loop-exit scope,
1408 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001409 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001410 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001411 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001412
Alexey Bataevddf3db92018-04-13 17:31:06 +00001413 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001414
Alexey Bataev2df54a02015-03-12 08:53:29 +00001415 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001416 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001417 if (ExitBlock != LoopExit.getBlock()) {
1418 EmitBlock(ExitBlock);
1419 EmitBranchThroughCleanup(LoopExit);
1420 }
1421
1422 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001423 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001424
1425 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001426 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001427 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1428
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001429 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001430
1431 // Emit "IV = IV + 1" and a back-edge to the condition block.
1432 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001433 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001434 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001435 BreakContinueStack.pop_back();
1436 EmitBranch(CondBlock);
1437 LoopStack.pop();
1438 // Emit the fall-through block.
1439 EmitBlock(LoopExit.getBlock());
1440}
1441
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001442bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001443 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001444 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001445 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001446 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001447 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001448 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001449 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001450 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1451 if (const auto *Ref =
1452 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001453 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001454 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001455 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001456 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1457 VD->getInit()->getType(), VK_LValue,
1458 VD->getInit()->getExprLoc());
1459 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1460 VD->getType()),
1461 /*capturedByInit=*/false);
1462 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001463 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001464 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001465 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001466 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001467 // Emit the linear steps for the linear clauses.
1468 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001469 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1470 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001471 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001472 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001473 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001474 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001475 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001476 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001477}
1478
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001479void CodeGenFunction::EmitOMPLinearClauseFinal(
1480 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001481 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001482 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001483 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001484 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001485 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001486 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001487 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001488 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001489 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001490 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001491 // If the first post-update expression is found, emit conditional
1492 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001493 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001494 DoneBB = createBasicBlock(".omp.linear.pu.done");
1495 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1496 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001497 }
1498 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001499 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001500 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001501 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001502 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001503 Address OrigAddr = EmitLValue(&DRE).getAddress();
1504 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001505 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001506 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001507 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001508 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001509 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001510 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001511 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001512 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001513 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001514 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001515}
1516
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001517static void emitAlignedClause(CodeGenFunction &CGF,
1518 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001519 if (!CGF.HaveInsertPoint())
1520 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001521 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Erich Keanef7593952019-10-11 14:59:44 +00001522 llvm::APInt ClauseAlignment(64, 0);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001523 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1524 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001525 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
Erich Keanef7593952019-10-11 14:59:44 +00001526 ClauseAlignment = AlignmentCI->getValue();
Alexander Musman09184fe2014-09-30 05:29:28 +00001527 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001528 for (const Expr *E : Clause->varlists()) {
Erich Keanef7593952019-10-11 14:59:44 +00001529 llvm::APInt Alignment(ClauseAlignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001530 if (Alignment == 0) {
1531 // OpenMP [2.8.1, Description]
1532 // If no optional parameter is specified, implementation-defined default
1533 // alignments for SIMD instructions on the target platforms are assumed.
1534 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001535 CGF.getContext()
1536 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1537 E->getType()->getPointeeType()))
1538 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001539 }
Erich Keanef7593952019-10-11 14:59:44 +00001540 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001541 "alignment is not power of 2");
1542 if (Alignment != 0) {
1543 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001544 CGF.EmitAlignmentAssumption(
Erich Keanef7593952019-10-11 14:59:44 +00001545 PtrValue, E, /*No second loc needed*/ SourceLocation(),
1546 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001547 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001548 }
1549 }
1550}
1551
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001552void CodeGenFunction::EmitOMPPrivateLoopCounters(
1553 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1554 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001555 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001556 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001557 for (const Expr *E : S.counters()) {
1558 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1559 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001560 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001561 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001562 EmitAutoVarCleanups(VarEmission);
1563 LocalDeclMap.erase(PrivateVD);
1564 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1565 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001566 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001567 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1568 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001569 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001570 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001571 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1572 E->getType(), VK_LValue, E->getExprLoc());
1573 return EmitLValue(&DRE).getAddress();
1574 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001575 } else {
1576 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1577 return VarEmission.getAllocatedAddress();
1578 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001579 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001580 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001581 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001582 // Privatize extra loop counters used in loops for ordered(n) clauses.
1583 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1584 if (!C->getNumForLoops())
1585 continue;
1586 for (unsigned I = S.getCollapsedNumber(),
1587 E = C->getLoopNumIterations().size();
1588 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001589 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001590 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001591 // Override only those variables that can be captured to avoid re-emission
1592 // of the variables declared within the loops.
1593 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001594 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1595 return CreateMemTemp(DRE->getType(), VD->getName());
1596 });
1597 }
1598 }
1599 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001600}
1601
Alexey Bataev62dbb972015-04-22 11:59:37 +00001602static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1603 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1604 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001605 if (!CGF.HaveInsertPoint())
1606 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001607 {
1608 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001609 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001610 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001611 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001612 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001613 CGF.EmitIgnoredExpr(I);
1614 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001615 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00001616 // Create temp loop control variables with their init values to support
1617 // non-rectangular loops.
1618 CodeGenFunction::OMPMapVars PreCondVars;
1619 for (const Expr * E: S.dependent_counters()) {
1620 if (!E)
1621 continue;
1622 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1623 "dependent counter must not be an iterator.");
1624 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1625 Address CounterAddr =
1626 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1627 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1628 }
1629 (void)PreCondVars.apply(CGF);
1630 for (const Expr *E : S.dependent_inits()) {
1631 if (!E)
1632 continue;
1633 CGF.EmitIgnoredExpr(E);
1634 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001635 // Check that loop is executed at least one time.
1636 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00001637 PreCondVars.restore(CGF);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001638}
1639
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001640void CodeGenFunction::EmitOMPLinearClause(
1641 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1642 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001643 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001644 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1645 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001646 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1647 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001648 SIMDLCVs.insert(
1649 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1650 }
1651 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001652 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001653 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001654 for (const Expr *E : C->varlists()) {
1655 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1656 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001657 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001658 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001659 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001660 // Emit private VarDecl with copy init.
1661 EmitVarDecl(*PrivateVD);
1662 return GetAddrOfLocalVar(PrivateVD);
1663 });
1664 assert(IsRegistered && "linear var already registered as private");
1665 // Silence the warning about unused variable.
1666 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001667 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001668 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001669 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001670 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001671 }
1672 }
1673}
1674
Alexey Bataev45bfad52015-08-21 12:19:04 +00001675static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001676 const OMPExecutableDirective &D,
1677 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001678 if (!CGF.HaveInsertPoint())
1679 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001680 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001681 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1682 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001683 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001684 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1685 // In presence of finite 'safelen', it may be unsafe to mark all
1686 // the memory instructions parallel, because loop-carried
1687 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001688 if (!IsMonotonic)
1689 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001690 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001691 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1692 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001693 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001694 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001695 // In presence of finite 'safelen', it may be unsafe to mark all
1696 // the memory instructions parallel, because loop-carried
1697 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001698 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001699 }
1700}
1701
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001702void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1703 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001704 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001705 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001706 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001707 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001708}
1709
Alexey Bataevef549a82016-03-09 09:49:09 +00001710void CodeGenFunction::EmitOMPSimdFinal(
1711 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001712 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001713 if (!HaveInsertPoint())
1714 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001715 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001716 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001717 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001718 for (const Expr *F : D.finals()) {
1719 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1720 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1721 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001722 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1723 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001724 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001725 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001726 // If the first post-update expression is found, emit conditional
1727 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001728 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001729 DoneBB = createBasicBlock(".omp.final.done");
1730 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1731 EmitBlock(ThenBB);
1732 }
1733 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001734 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001735 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001736 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001737 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001738 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001739 /*RefersToEnclosingVariableOrCapture=*/false,
1740 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1741 OrigAddr = EmitLValue(&DRE).getAddress();
1742 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001743 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001744 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001745 (void)VarScope.Privatize();
1746 EmitIgnoredExpr(F);
1747 }
1748 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001749 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001750 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001751 if (DoneBB)
1752 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001753}
1754
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001755static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1756 const OMPLoopDirective &S,
1757 CodeGenFunction::JumpDest LoopExit) {
1758 CGF.EmitOMPLoopBody(S, LoopExit);
1759 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001760}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001761
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001762/// Emit a helper variable and return corresponding lvalue.
1763static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1764 const DeclRefExpr *Helper) {
1765 auto VDecl = cast<VarDecl>(Helper->getDecl());
1766 CGF.EmitVarDecl(*VDecl);
1767 return CGF.EmitLValue(Helper);
1768}
1769
Alexey Bataevf8365372017-11-17 17:57:25 +00001770static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1771 PrePostActionTy &Action) {
1772 Action.Enter(CGF);
1773 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1774 "Expected simd directive");
1775 OMPLoopScope PreInitScope(CGF, S);
1776 // if (PreCond) {
1777 // for (IV in 0..LastIteration) BODY;
1778 // <Final counter/linear vars updates>;
1779 // }
1780 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001781 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1782 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1783 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1784 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1785 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1786 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001787
Alexey Bataevf8365372017-11-17 17:57:25 +00001788 // Emit: if (PreCond) - begin.
1789 // If the condition constant folds and can be elided, avoid emitting the
1790 // whole loop.
1791 bool CondConstant;
1792 llvm::BasicBlock *ContBlock = nullptr;
1793 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1794 if (!CondConstant)
1795 return;
1796 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001797 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001798 ContBlock = CGF.createBasicBlock("simd.if.end");
1799 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1800 CGF.getProfileCount(&S));
1801 CGF.EmitBlock(ThenBlock);
1802 CGF.incrementProfileCounter(&S);
1803 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001804
Alexey Bataevf8365372017-11-17 17:57:25 +00001805 // Emit the loop iteration variable.
1806 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001807 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001808 CGF.EmitVarDecl(*IVDecl);
1809 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001810
Alexey Bataevf8365372017-11-17 17:57:25 +00001811 // Emit the iterations count variable.
1812 // If it is not a variable, Sema decided to calculate iterations count on
1813 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001814 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001815 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1816 // Emit calculation of the iterations count.
1817 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1818 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001819
Alexey Bataevf8365372017-11-17 17:57:25 +00001820 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001821
Alexey Bataevf8365372017-11-17 17:57:25 +00001822 emitAlignedClause(CGF, S);
1823 (void)CGF.EmitOMPLinearClauseInit(S);
1824 {
1825 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1826 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1827 CGF.EmitOMPLinearClause(S, LoopScope);
1828 CGF.EmitOMPPrivateClause(S, LoopScope);
1829 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1830 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1831 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001832 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1833 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevf8365372017-11-17 17:57:25 +00001834 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1835 S.getInc(),
1836 [&S](CodeGenFunction &CGF) {
1837 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1838 CGF.EmitStopPoint(&S);
1839 },
1840 [](CodeGenFunction &) {});
Alexey Bataevddf3db92018-04-13 17:31:06 +00001841 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001842 // Emit final copy of the lastprivate variables at the end of loops.
1843 if (HasLastprivateClause)
1844 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1845 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001846 emitPostUpdateForReductionClause(CGF, S,
1847 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001848 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001849 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001850 // Emit: if (PreCond) - end.
1851 if (ContBlock) {
1852 CGF.EmitBranch(ContBlock);
1853 CGF.EmitBlock(ContBlock, true);
1854 }
1855}
1856
1857void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1858 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1859 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001860 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001861 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001862 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001863}
1864
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001865void CodeGenFunction::EmitOMPOuterLoop(
1866 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1867 CodeGenFunction::OMPPrivateScope &LoopScope,
1868 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1869 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1870 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001871 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001872
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001873 const Expr *IVExpr = S.getIterationVariable();
1874 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1875 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1876
Alexey Bataevddf3db92018-04-13 17:31:06 +00001877 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001878
1879 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001880 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001881 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001882 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001883 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1884 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001885
1886 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001887 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001888 // UB = min(UB, GlobalUB) or
1889 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1890 // 'distribute parallel for')
1891 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001892 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001893 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001894 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001895 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001896 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001897 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001898 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001899 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001900 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001901
1902 // If there are any cleanups between here and the loop-exit scope,
1903 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001904 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001905 if (LoopScope.requiresCleanups())
1906 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1907
Alexey Bataevddf3db92018-04-13 17:31:06 +00001908 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001909 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1910 if (ExitBlock != LoopExit.getBlock()) {
1911 EmitBlock(ExitBlock);
1912 EmitBranchThroughCleanup(LoopExit);
1913 }
1914 EmitBlock(LoopBody);
1915
Alexander Musman92bdaab2015-03-12 13:37:50 +00001916 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1917 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001918 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001919 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001920
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001921 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001922 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001923 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1924
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001925 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1926 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001927 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1928 LoopStack.setParallel(!IsMonotonic);
1929 else
1930 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001931
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001932 SourceLocation Loc = S.getBeginLoc();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001933
1934 // when 'distribute' is not combined with a 'for':
1935 // while (idx <= UB) { BODY; ++idx; }
1936 // when 'distribute' is combined with a 'for'
1937 // (e.g. 'distribute parallel for')
1938 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1939 EmitOMPInnerLoop(
1940 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1941 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1942 CodeGenLoop(CGF, S, LoopExit);
1943 },
1944 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1945 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1946 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001947
1948 EmitBlock(Continue.getBlock());
1949 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001950 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001951 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001952 EmitIgnoredExpr(LoopArgs.NextLB);
1953 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001954 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001955
1956 EmitBranch(CondBlock);
1957 LoopStack.pop();
1958 // Emit the fall-through block.
1959 EmitBlock(LoopExit.getBlock());
1960
1961 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001962 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1963 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001964 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00001965 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001966 };
1967 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001968}
1969
1970void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001971 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001972 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001973 const OMPLoopArguments &LoopArgs,
1974 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001975 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001976
1977 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001978 const bool DynamicOrOrdered =
1979 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001980
1981 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001982 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001983 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001984 "static non-chunked schedule does not need outer loop");
1985
1986 // Emit outer loop.
1987 //
1988 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1989 // When schedule(dynamic,chunk_size) is specified, the iterations are
1990 // distributed to threads in the team in chunks as the threads request them.
1991 // Each thread executes a chunk of iterations, then requests another chunk,
1992 // until no chunks remain to be distributed. Each chunk contains chunk_size
1993 // iterations, except for the last chunk to be distributed, which may have
1994 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1995 //
1996 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1997 // to threads in the team in chunks as the executing threads request them.
1998 // Each thread executes a chunk of iterations, then requests another chunk,
1999 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2000 // each chunk is proportional to the number of unassigned iterations divided
2001 // by the number of threads in the team, decreasing to 1. For a chunk_size
2002 // with value k (greater than 1), the size of each chunk is determined in the
2003 // same way, with the restriction that the chunks do not contain fewer than k
2004 // iterations (except for the last chunk to be assigned, which may have fewer
2005 // than k iterations).
2006 //
2007 // When schedule(auto) is specified, the decision regarding scheduling is
2008 // delegated to the compiler and/or runtime system. The programmer gives the
2009 // implementation the freedom to choose any possible mapping of iterations to
2010 // threads in the team.
2011 //
2012 // When schedule(runtime) is specified, the decision regarding scheduling is
2013 // deferred until run time, and the schedule and chunk size are taken from the
2014 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2015 // implementation defined
2016 //
2017 // while(__kmpc_dispatch_next(&LB, &UB)) {
2018 // idx = LB;
2019 // while (idx <= UB) { BODY; ++idx;
2020 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2021 // } // inner loop
2022 // }
2023 //
2024 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2025 // When schedule(static, chunk_size) is specified, iterations are divided into
2026 // chunks of size chunk_size, and the chunks are assigned to the threads in
2027 // the team in a round-robin fashion in the order of the thread number.
2028 //
2029 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2030 // while (idx <= UB) { BODY; ++idx; } // inner loop
2031 // LB = LB + ST;
2032 // UB = UB + ST;
2033 // }
2034 //
2035
2036 const Expr *IVExpr = S.getIterationVariable();
2037 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2038 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2039
2040 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002041 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2042 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002043 llvm::Value *LBVal = DispatchBounds.first;
2044 llvm::Value *UBVal = DispatchBounds.second;
2045 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2046 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002047 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002048 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002049 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002050 CGOpenMPRuntime::StaticRTInput StaticInit(
2051 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2052 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002053 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002054 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002055 }
2056
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002057 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2058 const unsigned IVSize,
2059 const bool IVSigned) {
2060 if (Ordered) {
2061 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2062 IVSigned);
2063 }
2064 };
2065
2066 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2067 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2068 OuterLoopArgs.IncExpr = S.getInc();
2069 OuterLoopArgs.Init = S.getInit();
2070 OuterLoopArgs.Cond = S.getCond();
2071 OuterLoopArgs.NextLB = S.getNextLowerBound();
2072 OuterLoopArgs.NextUB = S.getNextUpperBound();
2073 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2074 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002075}
2076
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002077static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2078 const unsigned IVSize, const bool IVSigned) {}
2079
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002080void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002081 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2082 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2083 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002084
Alexey Bataevddf3db92018-04-13 17:31:06 +00002085 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002086
2087 // Emit outer loop.
2088 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2089 // dynamic
2090 //
2091
2092 const Expr *IVExpr = S.getIterationVariable();
2093 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2094 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2095
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002096 CGOpenMPRuntime::StaticRTInput StaticInit(
2097 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2098 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002099 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002100
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002101 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002102 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002103 Expr *IncExpr;
2104 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2105 IncExpr = S.getDistInc();
2106 else
2107 IncExpr = S.getInc();
2108
2109 // this routine is shared by 'omp distribute parallel for' and
2110 // 'omp distribute': select the right EUB expression depending on the
2111 // directive
2112 OMPLoopArguments OuterLoopArgs;
2113 OuterLoopArgs.LB = LoopArgs.LB;
2114 OuterLoopArgs.UB = LoopArgs.UB;
2115 OuterLoopArgs.ST = LoopArgs.ST;
2116 OuterLoopArgs.IL = LoopArgs.IL;
2117 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2118 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2119 ? S.getCombinedEnsureUpperBound()
2120 : S.getEnsureUpperBound();
2121 OuterLoopArgs.IncExpr = IncExpr;
2122 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2123 ? S.getCombinedInit()
2124 : S.getInit();
2125 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2126 ? S.getCombinedCond()
2127 : S.getCond();
2128 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2129 ? S.getCombinedNextLowerBound()
2130 : S.getNextLowerBound();
2131 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2132 ? S.getCombinedNextUpperBound()
2133 : S.getNextUpperBound();
2134
2135 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2136 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2137 emitEmptyOrdered);
2138}
2139
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002140static std::pair<LValue, LValue>
2141emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2142 const OMPExecutableDirective &S) {
2143 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2144 LValue LB =
2145 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2146 LValue UB =
2147 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2148
2149 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2150 // parallel for') we need to use the 'distribute'
2151 // chunk lower and upper bounds rather than the whole loop iteration
2152 // space. These are parameters to the outlined function for 'parallel'
2153 // and we copy the bounds of the previous schedule into the
2154 // the current ones.
2155 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2156 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002157 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2158 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002159 PrevLBVal = CGF.EmitScalarConversion(
2160 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002161 LS.getIterationVariable()->getType(),
2162 LS.getPrevLowerBoundVariable()->getExprLoc());
2163 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2164 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002165 PrevUBVal = CGF.EmitScalarConversion(
2166 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002167 LS.getIterationVariable()->getType(),
2168 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002169
2170 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2171 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2172
2173 return {LB, UB};
2174}
2175
2176/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2177/// we need to use the LB and UB expressions generated by the worksharing
2178/// code generation support, whereas in non combined situations we would
2179/// just emit 0 and the LastIteration expression
2180/// This function is necessary due to the difference of the LB and UB
2181/// types for the RT emission routines for 'for_static_init' and
2182/// 'for_dispatch_init'
2183static std::pair<llvm::Value *, llvm::Value *>
2184emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2185 const OMPExecutableDirective &S,
2186 Address LB, Address UB) {
2187 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2188 const Expr *IVExpr = LS.getIterationVariable();
2189 // when implementing a dynamic schedule for a 'for' combined with a
2190 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2191 // is not normalized as each team only executes its own assigned
2192 // distribute chunk
2193 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002194 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002195 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002196 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002197 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002198 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002199}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002200
2201static void emitDistributeParallelForDistributeInnerBoundParams(
2202 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2203 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2204 const auto &Dir = cast<OMPLoopDirective>(S);
2205 LValue LB =
2206 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002207 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002208 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2209 CapturedVars.push_back(LBCast);
2210 LValue UB =
2211 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2212
Alexey Bataevddf3db92018-04-13 17:31:06 +00002213 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002214 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2215 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002216}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002217
2218static void
2219emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2220 const OMPLoopDirective &S,
2221 CodeGenFunction::JumpDest LoopExit) {
2222 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002223 PrePostActionTy &Action) {
2224 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002225 bool HasCancel = false;
2226 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2227 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2228 HasCancel = D->hasCancel();
2229 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2230 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002231 else if (const auto *D =
2232 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2233 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002234 }
2235 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2236 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002237 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2238 emitDistributeParallelForInnerBounds,
2239 emitDistributeParallelForDispatchBounds);
2240 };
2241
2242 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002243 CGF, S,
2244 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2245 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002246 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002247}
2248
Carlo Bertolli9925f152016-06-27 14:55:37 +00002249void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2250 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002251 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2252 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2253 S.getDistInc());
2254 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002255 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002256 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002257}
2258
Kelvin Li4a39add2016-07-05 05:00:15 +00002259void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2260 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002261 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2262 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2263 S.getDistInc());
2264 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002265 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002266 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002267}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002268
2269void CodeGenFunction::EmitOMPDistributeSimdDirective(
2270 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002271 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2272 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2273 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002274 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002275 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002276}
2277
Alexey Bataevf8365372017-11-17 17:57:25 +00002278void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2279 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2280 // Emit SPMD target parallel for region as a standalone region.
2281 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2282 emitOMPSimdRegion(CGF, S, Action);
2283 };
2284 llvm::Function *Fn;
2285 llvm::Constant *Addr;
2286 // Emit target region as a standalone region.
2287 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2288 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2289 assert(Fn && Addr && "Target device function emission failed.");
2290}
2291
Kelvin Li986330c2016-07-20 22:57:10 +00002292void CodeGenFunction::EmitOMPTargetSimdDirective(
2293 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002294 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2295 emitOMPSimdRegion(CGF, S, Action);
2296 };
2297 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002298}
2299
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002300namespace {
2301 struct ScheduleKindModifiersTy {
2302 OpenMPScheduleClauseKind Kind;
2303 OpenMPScheduleClauseModifier M1;
2304 OpenMPScheduleClauseModifier M2;
2305 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2306 OpenMPScheduleClauseModifier M1,
2307 OpenMPScheduleClauseModifier M2)
2308 : Kind(Kind), M1(M1), M2(M2) {}
2309 };
2310} // namespace
2311
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002312bool CodeGenFunction::EmitOMPWorksharingLoop(
2313 const OMPLoopDirective &S, Expr *EUB,
2314 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2315 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002316 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002317 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2318 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002319 EmitVarDecl(*IVDecl);
2320
2321 // Emit the iterations count variable.
2322 // If it is not a variable, Sema decided to calculate iterations count on each
2323 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002324 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002325 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2326 // Emit calculation of the iterations count.
2327 EmitIgnoredExpr(S.getCalcLastIteration());
2328 }
2329
Alexey Bataevddf3db92018-04-13 17:31:06 +00002330 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002331
Alexey Bataev38e89532015-04-16 04:54:05 +00002332 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002333 // Check pre-condition.
2334 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002335 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002336 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002337 // If the condition constant folds and can be elided, avoid emitting the
2338 // whole loop.
2339 bool CondConstant;
2340 llvm::BasicBlock *ContBlock = nullptr;
2341 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2342 if (!CondConstant)
2343 return false;
2344 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002345 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002346 ContBlock = createBasicBlock("omp.precond.end");
2347 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002348 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002349 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002350 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002351 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002352
Alexey Bataevea33dee2018-02-15 23:39:43 +00002353 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002354 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002355 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002356 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002357 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002358 else
2359 Ordered = true;
2360 }
2361
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002362 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002363 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002364 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002365 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002366
2367 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2368 LValue LB = Bounds.first;
2369 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002370 LValue ST =
2371 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2372 LValue IL =
2373 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2374
Alexander Musmanc6388682014-12-15 07:07:06 +00002375 // Emit 'then' code.
2376 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002377 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002378 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002379 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002380 // initialization of firstprivate variables and post-update of
2381 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002382 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002383 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002384 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002385 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002386 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002387 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002388 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002389 EmitOMPPrivateLoopCounters(S, LoopScope);
2390 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002391 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002392 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2393 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002394
2395 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002396 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002397 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002398 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002399 ScheduleKind.Schedule = C->getScheduleKind();
2400 ScheduleKind.M1 = C->getFirstScheduleModifier();
2401 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002402 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002403 } else {
2404 // Default behaviour for schedule clause.
2405 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002406 *this, S, ScheduleKind.Schedule, ChunkExpr);
2407 }
2408 bool HasChunkSizeOne = false;
2409 llvm::Value *Chunk = nullptr;
2410 if (ChunkExpr) {
2411 Chunk = EmitScalarExpr(ChunkExpr);
2412 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2413 S.getIterationVariable()->getType(),
2414 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002415 Expr::EvalResult Result;
2416 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2417 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002418 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002419 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002420 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002421 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2422 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002423 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2424 // If the static schedule kind is specified or if the ordered clause is
2425 // specified, and if no monotonic modifier is specified, the effect will
2426 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002427 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2428 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2429 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2430 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2431 /* Chunked */ Chunk != nullptr) ||
2432 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002433 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002434 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2435 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002436 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2437 // When no chunk_size is specified, the iteration space is divided into
2438 // chunks that are approximately equal in size, and at most one chunk is
2439 // distributed to each thread. Note that the size of the chunks is
2440 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002441 CGOpenMPRuntime::StaticRTInput StaticInit(
2442 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002443 UB.getAddress(), ST.getAddress(),
2444 StaticChunkedOne ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002445 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002446 ScheduleKind, StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002447 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002448 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002449 // UB = min(UB, GlobalUB);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002450 if (!StaticChunkedOne)
2451 EmitIgnoredExpr(S.getEnsureUpperBound());
Alexander Musmanc6388682014-12-15 07:07:06 +00002452 // IV = LB;
2453 EmitIgnoredExpr(S.getInit());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002454 // For unchunked static schedule generate:
2455 //
2456 // while (idx <= UB) {
2457 // BODY;
2458 // ++idx;
2459 // }
2460 //
2461 // For static schedule with chunk one:
2462 //
2463 // while (IV <= PrevUB) {
2464 // BODY;
2465 // IV += ST;
2466 // }
2467 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
2468 StaticChunkedOne ? S.getCombinedParForInDistCond() : S.getCond(),
2469 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2470 [&S, LoopExit](CodeGenFunction &CGF) {
2471 CGF.EmitOMPLoopBody(S, LoopExit);
2472 CGF.EmitStopPoint(&S);
2473 },
2474 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002475 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002476 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002477 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002478 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002479 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002480 };
2481 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002482 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002483 const bool IsMonotonic =
2484 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2485 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2486 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2487 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002488 // Emit the outer loop, which requests its work chunk [LB..UB] from
2489 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002490 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2491 ST.getAddress(), IL.getAddress(),
2492 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002493 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002494 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002495 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002496 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002497 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2498 return CGF.Builder.CreateIsNotNull(
2499 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2500 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002501 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002502 EmitOMPReductionClauseFinal(
2503 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2504 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2505 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002506 // Emit post-update of the reduction variables if IsLastIter != 0.
2507 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002508 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002509 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002510 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002511 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002512 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2513 if (HasLastprivateClause)
2514 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002515 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002516 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002517 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002518 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002519 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002520 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002521 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002522 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002523 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002524 if (ContBlock) {
2525 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002526 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002527 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002528 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002529 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002530}
2531
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002532/// The following two functions generate expressions for the loop lower
2533/// and upper bounds in case of static and dynamic (dispatch) schedule
2534/// of the associated 'for' or 'distribute' loop.
2535static std::pair<LValue, LValue>
2536emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002537 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002538 LValue LB =
2539 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2540 LValue UB =
2541 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2542 return {LB, UB};
2543}
2544
2545/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2546/// consider the lower and upper bound expressions generated by the
2547/// worksharing loop support, but we use 0 and the iteration space size as
2548/// constants
2549static std::pair<llvm::Value *, llvm::Value *>
2550emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2551 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002552 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002553 const Expr *IVExpr = LS.getIterationVariable();
2554 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2555 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2556 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2557 return {LBVal, UBVal};
2558}
2559
Alexander Musmanc6388682014-12-15 07:07:06 +00002560void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002561 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2563 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002564 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002565 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2566 emitForLoopBounds,
2567 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002568 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002569 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002570 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002571 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2572 S.hasCancel());
2573 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002574
2575 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002576 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002577 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002578}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002579
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002580void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002581 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002582 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2583 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002584 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2585 emitForLoopBounds,
2586 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002587 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002588 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002589 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002590 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2591 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002592
2593 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002594 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002595 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002596}
2597
Alexey Bataev2df54a02015-03-12 08:53:29 +00002598static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2599 const Twine &Name,
2600 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002601 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002602 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002603 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002604 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002605}
2606
Alexey Bataev3392d762016-02-16 11:18:12 +00002607void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002608 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2609 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002610 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002611 auto &&CodeGen = [&S, CapturedStmt, CS,
2612 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2613 ASTContext &C = CGF.getContext();
2614 QualType KmpInt32Ty =
2615 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002616 // Emit helper vars inits.
2617 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2618 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002619 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2620 ? CGF.Builder.getInt32(CS->size() - 1)
2621 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002622 LValue UB =
2623 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2624 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2625 CGF.Builder.getInt32(1));
2626 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2627 CGF.Builder.getInt32(0));
2628 // Loop counter.
2629 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002630 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002631 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002632 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002633 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2634 // Generate condition for loop.
2635 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002636 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002637 // Increment for loop counter.
2638 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002639 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002640 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002641 // Iterate through all sections and emit a switch construct:
2642 // switch (IV) {
2643 // case 0:
2644 // <SectionStmt[0]>;
2645 // break;
2646 // ...
2647 // case <NumSection> - 1:
2648 // <SectionStmt[<NumSection> - 1]>;
2649 // break;
2650 // }
2651 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002652 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2653 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002654 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002655 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002656 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002657 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002658 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002659 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2660 CGF.EmitBlock(CaseBB);
2661 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002662 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002663 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002664 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002665 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002666 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002667 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002668 CGF.EmitBlock(CaseBB);
2669 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002670 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002671 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002672 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002673 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002674 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002675
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002676 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2677 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002678 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002679 // initialization of firstprivate variables and post-update of lastprivate
2680 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002681 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002682 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002683 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002684 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002685 CGF.EmitOMPPrivateClause(S, LoopScope);
2686 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2687 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2688 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002689 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2690 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002691
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002692 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002693 OpenMPScheduleTy ScheduleKind;
2694 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002695 CGOpenMPRuntime::StaticRTInput StaticInit(
2696 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2697 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002698 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002699 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002700 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002701 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002702 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002703 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2704 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2705 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002706 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002707 // while (idx <= UB) { BODY; ++idx; }
2708 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2709 [](CodeGenFunction &) {});
2710 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002711 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002712 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002713 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002714 };
2715 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002716 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002717 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002718 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2719 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002720 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002721 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002722
2723 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2724 if (HasLastprivates)
2725 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002726 S, /*NoFinals=*/false,
2727 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002728 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002729 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002730
2731 bool HasCancel = false;
2732 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2733 HasCancel = OSD->hasCancel();
2734 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2735 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002736 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002737 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2738 HasCancel);
2739 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2740 // clause. Otherwise the barrier will be generated by the codegen for the
2741 // directive.
2742 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002743 // Emit implicit barrier to synchronize threads and avoid data races on
2744 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002745 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002746 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002747 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002748}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002749
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002750void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002751 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002752 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002753 EmitSections(S);
2754 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002755 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002756 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002757 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002758 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002759 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002760}
2761
2762void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002763 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002764 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002765 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002766 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002767 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2768 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002769}
2770
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002771void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002772 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002773 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002774 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002775 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002776 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002777 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002778 // Build a list of copyprivate variables along with helper expressions
2779 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002780 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002781 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002782 DestExprs.append(C->destination_exprs().begin(),
2783 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002784 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002785 AssignmentOps.append(C->assignment_ops().begin(),
2786 C->assignment_ops().end());
2787 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002788 // Emit code for 'single' region along with 'copyprivate' clauses
2789 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2790 Action.Enter(CGF);
2791 OMPPrivateScope SingleScope(CGF);
2792 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2793 CGF.EmitOMPPrivateClause(S, SingleScope);
2794 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002795 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002796 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002797 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002798 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002799 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002800 CopyprivateVars, DestExprs,
2801 SrcExprs, AssignmentOps);
2802 }
2803 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2804 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002805 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002806 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002807 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002808 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002809 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002810}
2811
Alexey Bataev8d690652014-12-04 07:23:53 +00002812void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002813 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2814 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002815 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002816 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002817 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002818 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002819}
2820
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002821void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002822 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2823 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002824 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002825 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002826 const Expr *Hint = nullptr;
2827 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002828 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002829 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002830 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2831 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002832 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002833}
2834
Alexey Bataev671605e2015-04-13 05:28:11 +00002835void CodeGenFunction::EmitOMPParallelForDirective(
2836 const OMPParallelForDirective &S) {
2837 // Emit directive as a combined directive that consists of two implicit
2838 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002839 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2840 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002841 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002842 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2843 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002844 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002845 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2846 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002847}
2848
Alexander Musmane4e893b2014-09-23 09:33:00 +00002849void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002850 const OMPParallelForSimdDirective &S) {
2851 // Emit directive as a combined directive that consists of two implicit
2852 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002853 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2854 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002855 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2856 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002857 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002858 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2859 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002860}
2861
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002862void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002863 const OMPParallelSectionsDirective &S) {
2864 // Emit directive as a combined directive that consists of two implicit
2865 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002866 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2867 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002868 CGF.EmitSections(S);
2869 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002870 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2871 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002872}
2873
Alexey Bataev475a7442018-01-12 19:39:11 +00002874void CodeGenFunction::EmitOMPTaskBasedDirective(
2875 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2876 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2877 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002878 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002879 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002880 auto I = CS->getCapturedDecl()->param_begin();
2881 auto PartId = std::next(I);
2882 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002883 // Check if the task is final
2884 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2885 // If the condition constant folds and can be elided, try to avoid emitting
2886 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002887 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002888 bool CondConstant;
2889 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2890 Data.Final.setInt(CondConstant);
2891 else
2892 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2893 } else {
2894 // By default the task is not final.
2895 Data.Final.setInt(/*IntVal=*/false);
2896 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002897 // Check if the task has 'priority' clause.
2898 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002899 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002900 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002901 Data.Priority.setPointer(EmitScalarConversion(
2902 EmitScalarExpr(Prio), Prio->getType(),
2903 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2904 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002905 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002906 // The first function argument for tasks is a thread id, the second one is a
2907 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002908 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2909 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002910 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002911 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002912 for (const Expr *IInit : C->private_copies()) {
2913 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002914 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002915 Data.PrivateVars.push_back(*IRef);
2916 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002917 }
2918 ++IRef;
2919 }
2920 }
2921 EmittedAsPrivate.clear();
2922 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002923 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002924 auto IRef = C->varlist_begin();
2925 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002926 for (const Expr *IInit : C->private_copies()) {
2927 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002928 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002929 Data.FirstprivateVars.push_back(*IRef);
2930 Data.FirstprivateCopies.push_back(IInit);
2931 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002932 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002933 ++IRef;
2934 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002935 }
2936 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002937 // Get list of lastprivate variables (for taskloops).
2938 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2939 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2940 auto IRef = C->varlist_begin();
2941 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002942 for (const Expr *IInit : C->private_copies()) {
2943 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002944 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2945 Data.LastprivateVars.push_back(*IRef);
2946 Data.LastprivateCopies.push_back(IInit);
2947 }
2948 LastprivateDstsOrigs.insert(
2949 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2950 cast<DeclRefExpr>(*IRef)});
2951 ++IRef;
2952 ++ID;
2953 }
2954 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002955 SmallVector<const Expr *, 4> LHSs;
2956 SmallVector<const Expr *, 4> RHSs;
2957 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2958 auto IPriv = C->privates().begin();
2959 auto IRed = C->reduction_ops().begin();
2960 auto ILHS = C->lhs_exprs().begin();
2961 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002962 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002963 Data.ReductionVars.emplace_back(Ref);
2964 Data.ReductionCopies.emplace_back(*IPriv);
2965 Data.ReductionOps.emplace_back(*IRed);
2966 LHSs.emplace_back(*ILHS);
2967 RHSs.emplace_back(*IRHS);
2968 std::advance(IPriv, 1);
2969 std::advance(IRed, 1);
2970 std::advance(ILHS, 1);
2971 std::advance(IRHS, 1);
2972 }
2973 }
2974 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002975 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002976 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002977 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00002978 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00002979 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00002980 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2981 CapturedRegion](CodeGenFunction &CGF,
2982 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002983 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002984 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002985 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2986 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00002987 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
2988 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00002989 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002990 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
2991 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
2992 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
2993 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00002994 // Map privates.
2995 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2996 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2997 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002998 for (const Expr *E : Data.PrivateVars) {
2999 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003000 Address PrivatePtr = CGF.CreateMemTemp(
3001 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003002 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003003 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003004 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003005 for (const Expr *E : Data.FirstprivateVars) {
3006 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003007 Address PrivatePtr =
3008 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3009 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003010 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003011 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003012 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003013 for (const Expr *E : Data.LastprivateVars) {
3014 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003015 Address PrivatePtr =
3016 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3017 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003018 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003019 CallArgs.push_back(PrivatePtr.getPointer());
3020 }
James Y Knight9871db02019-02-05 16:42:33 +00003021 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3022 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003023 for (const auto &Pair : LastprivateDstsOrigs) {
3024 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003025 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3026 /*RefersToEnclosingVariableOrCapture=*/
3027 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3028 Pair.second->getType(), VK_LValue,
3029 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003030 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
3031 return CGF.EmitLValue(&DRE).getAddress();
3032 });
3033 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003034 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003035 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3036 CGF.getContext().getDeclAlign(Pair.first));
3037 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3038 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003039 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003040 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003041 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003042 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3043 Data.ReductionOps);
3044 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3045 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3046 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3047 RedCG.emitSharedLValue(CGF, Cnt);
3048 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003049 // FIXME: This must removed once the runtime library is fixed.
3050 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003051 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003052 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003053 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003054 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003055 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003056 Replacement =
3057 Address(CGF.EmitScalarConversion(
3058 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3059 CGF.getContext().getPointerType(
3060 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003061 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003062 Replacement.getAlignment());
3063 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3064 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3065 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003066 }
3067 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003068 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003069 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003070 SmallVector<const Expr *, 4> InRedVars;
3071 SmallVector<const Expr *, 4> InRedPrivs;
3072 SmallVector<const Expr *, 4> InRedOps;
3073 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3074 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3075 auto IPriv = C->privates().begin();
3076 auto IRed = C->reduction_ops().begin();
3077 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003078 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003079 InRedVars.emplace_back(Ref);
3080 InRedPrivs.emplace_back(*IPriv);
3081 InRedOps.emplace_back(*IRed);
3082 TaskgroupDescriptors.emplace_back(*ITD);
3083 std::advance(IPriv, 1);
3084 std::advance(IRed, 1);
3085 std::advance(ITD, 1);
3086 }
3087 }
3088 // Privatize in_reduction items here, because taskgroup descriptors must be
3089 // privatized earlier.
3090 OMPPrivateScope InRedScope(CGF);
3091 if (!InRedVars.empty()) {
3092 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3093 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3094 RedCG.emitSharedLValue(CGF, Cnt);
3095 RedCG.emitAggregateType(CGF, Cnt);
3096 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003097 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003098 // FIXME: This must removed once the runtime library is fixed.
3099 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003100 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003101 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003102 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003103 llvm::Value *ReductionsPtr =
3104 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3105 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003106 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003107 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003108 Replacement = Address(
3109 CGF.EmitScalarConversion(
3110 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3111 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003112 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003113 Replacement.getAlignment());
3114 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3115 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3116 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003117 }
3118 }
3119 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003120
3121 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003122 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003123 };
James Y Knight9871db02019-02-05 16:42:33 +00003124 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003125 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3126 Data.NumberOfParts);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003127 OMPLexicalScope Scope(*this, S, llvm::None,
3128 !isOpenMPParallelDirective(S.getDirectiveKind()));
Alexey Bataev7292c292016-04-25 12:22:29 +00003129 TaskGen(*this, OutlinedFn, Data);
3130}
3131
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003132static ImplicitParamDecl *
3133createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003134 QualType Ty, CapturedDecl *CD,
3135 SourceLocation Loc) {
3136 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3137 ImplicitParamDecl::Other);
3138 auto *OrigRef = DeclRefExpr::Create(
3139 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3140 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3141 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3142 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003143 auto *PrivateRef = DeclRefExpr::Create(
3144 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003145 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003146 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003147 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3148 ImplicitParamDecl::Other);
3149 auto *InitRef = DeclRefExpr::Create(
3150 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3151 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003152 PrivateVD->setInitStyle(VarDecl::CInit);
3153 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3154 InitRef, /*BasePath=*/nullptr,
3155 VK_RValue));
3156 Data.FirstprivateVars.emplace_back(OrigRef);
3157 Data.FirstprivateCopies.emplace_back(PrivateRef);
3158 Data.FirstprivateInits.emplace_back(InitRef);
3159 return OrigVD;
3160}
3161
3162void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3163 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3164 OMPTargetDataInfo &InputInfo) {
3165 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003166 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3167 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3168 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3169 auto I = CS->getCapturedDecl()->param_begin();
3170 auto PartId = std::next(I);
3171 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003172 OMPTaskDataTy Data;
3173 // The task is not final.
3174 Data.Final.setInt(/*IntVal=*/false);
3175 // Get list of firstprivate variables.
3176 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3177 auto IRef = C->varlist_begin();
3178 auto IElemInitRef = C->inits().begin();
3179 for (auto *IInit : C->private_copies()) {
3180 Data.FirstprivateVars.push_back(*IRef);
3181 Data.FirstprivateCopies.push_back(IInit);
3182 Data.FirstprivateInits.push_back(*IElemInitRef);
3183 ++IRef;
3184 ++IElemInitRef;
3185 }
3186 }
3187 OMPPrivateScope TargetScope(*this);
3188 VarDecl *BPVD = nullptr;
3189 VarDecl *PVD = nullptr;
3190 VarDecl *SVD = nullptr;
3191 if (InputInfo.NumberOfTargetItems > 0) {
3192 auto *CD = CapturedDecl::Create(
3193 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3194 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3195 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003196 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003197 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003198 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003199 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003200 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003201 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003202 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003203 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003204 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003205 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003206 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003207 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003208 TargetScope.addPrivate(
3209 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3210 TargetScope.addPrivate(PVD,
3211 [&InputInfo]() { return InputInfo.PointersArray; });
3212 TargetScope.addPrivate(SVD,
3213 [&InputInfo]() { return InputInfo.SizesArray; });
3214 }
3215 (void)TargetScope.Privatize();
3216 // Build list of dependences.
3217 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003218 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003219 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003220 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3221 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3222 // Set proper addresses for generated private copies.
3223 OMPPrivateScope Scope(CGF);
3224 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003225 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3226 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003227 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003228 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3229 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3230 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3231 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003232 // Map privates.
3233 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3234 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3235 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003236 for (const Expr *E : Data.FirstprivateVars) {
3237 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003238 Address PrivatePtr =
3239 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3240 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003241 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003242 CallArgs.push_back(PrivatePtr.getPointer());
3243 }
James Y Knight9871db02019-02-05 16:42:33 +00003244 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3245 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003246 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003247 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3248 CGF.getContext().getDeclAlign(Pair.first));
3249 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3250 }
3251 }
3252 // Privatize all private variables except for in_reduction items.
3253 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003254 if (InputInfo.NumberOfTargetItems > 0) {
3255 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003256 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003257 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003258 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003259 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003260 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003261 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003262
3263 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003264 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003265 BodyGen(CGF);
3266 };
James Y Knight9871db02019-02-05 16:42:33 +00003267 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003268 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3269 Data.NumberOfParts);
3270 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3271 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3272 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3273 SourceLocation());
3274
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003275 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003276 SharedsTy, CapturedStruct, &IfCond, Data);
3277}
3278
Alexey Bataev7292c292016-04-25 12:22:29 +00003279void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3280 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003281 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003282 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3283 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003284 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003285 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3286 if (C->getNameModifier() == OMPD_unknown ||
3287 C->getNameModifier() == OMPD_task) {
3288 IfCond = C->getCondition();
3289 break;
3290 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003291 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003292
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003293 OMPTaskDataTy Data;
3294 // Check if we should emit tied or untied task.
3295 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003296 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3297 CGF.EmitStmt(CS->getCapturedStmt());
3298 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003299 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003300 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003301 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003302 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003303 SharedsTy, CapturedStruct, IfCond,
3304 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003305 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003306 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003307}
3308
Alexey Bataev9f797f32015-02-05 05:57:51 +00003309void CodeGenFunction::EmitOMPTaskyieldDirective(
3310 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003311 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003312}
3313
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003314void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003315 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003316}
3317
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003318void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003319 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003320}
3321
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003322void CodeGenFunction::EmitOMPTaskgroupDirective(
3323 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003324 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3325 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003326 if (const Expr *E = S.getReductionRef()) {
3327 SmallVector<const Expr *, 4> LHSs;
3328 SmallVector<const Expr *, 4> RHSs;
3329 OMPTaskDataTy Data;
3330 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3331 auto IPriv = C->privates().begin();
3332 auto IRed = C->reduction_ops().begin();
3333 auto ILHS = C->lhs_exprs().begin();
3334 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003335 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003336 Data.ReductionVars.emplace_back(Ref);
3337 Data.ReductionCopies.emplace_back(*IPriv);
3338 Data.ReductionOps.emplace_back(*IRed);
3339 LHSs.emplace_back(*ILHS);
3340 RHSs.emplace_back(*IRHS);
3341 std::advance(IPriv, 1);
3342 std::advance(IRed, 1);
3343 std::advance(ILHS, 1);
3344 std::advance(IRHS, 1);
3345 }
3346 }
3347 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003348 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003349 LHSs, RHSs, Data);
3350 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3351 CGF.EmitVarDecl(*VD);
3352 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3353 /*Volatile=*/false, E->getType());
3354 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003355 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003356 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003357 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003358 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003359}
3360
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003361void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003362 CGM.getOpenMPRuntime().emitFlush(
3363 *this,
3364 [&S]() -> ArrayRef<const Expr *> {
3365 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3366 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3367 FlushClause->varlist_end());
3368 return llvm::None;
3369 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003370 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003371}
3372
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003373void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3374 const CodeGenLoopTy &CodeGenLoop,
3375 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003376 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003377 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3378 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003379 EmitVarDecl(*IVDecl);
3380
3381 // Emit the iterations count variable.
3382 // If it is not a variable, Sema decided to calculate iterations count on each
3383 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003384 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3386 // Emit calculation of the iterations count.
3387 EmitIgnoredExpr(S.getCalcLastIteration());
3388 }
3389
Alexey Bataevddf3db92018-04-13 17:31:06 +00003390 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003391
Carlo Bertolli962bb802017-01-03 18:24:42 +00003392 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003393 // Check pre-condition.
3394 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003395 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003396 // Skip the entire loop if we don't meet the precondition.
3397 // If the condition constant folds and can be elided, avoid emitting the
3398 // whole loop.
3399 bool CondConstant;
3400 llvm::BasicBlock *ContBlock = nullptr;
3401 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3402 if (!CondConstant)
3403 return;
3404 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003405 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003406 ContBlock = createBasicBlock("omp.precond.end");
3407 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3408 getProfileCount(&S));
3409 EmitBlock(ThenBlock);
3410 incrementProfileCounter(&S);
3411 }
3412
Alexey Bataev617db5f2017-12-04 15:38:33 +00003413 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003414 // Emit 'then' code.
3415 {
3416 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003417
3418 LValue LB = EmitOMPHelperVar(
3419 *this, cast<DeclRefExpr>(
3420 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3421 ? S.getCombinedLowerBoundVariable()
3422 : S.getLowerBoundVariable())));
3423 LValue UB = EmitOMPHelperVar(
3424 *this, cast<DeclRefExpr>(
3425 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3426 ? S.getCombinedUpperBoundVariable()
3427 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003428 LValue ST =
3429 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3430 LValue IL =
3431 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3432
3433 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003434 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003435 // Emit implicit barrier to synchronize threads and avoid data races
3436 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003437 // lastprivate variables.
3438 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003439 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003440 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003441 }
3442 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003443 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003444 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3445 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003446 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003447 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003448 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003449 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003450 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3451 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003452
3453 // Detect the distribute schedule kind and chunk.
3454 llvm::Value *Chunk = nullptr;
3455 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003456 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003457 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003458 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003459 Chunk = EmitScalarExpr(Ch);
3460 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003461 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003462 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003463 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003464 } else {
3465 // Default behaviour for dist_schedule clause.
3466 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3467 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003468 }
3469 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3470 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3471
3472 // OpenMP [2.10.8, distribute Construct, Description]
3473 // If dist_schedule is specified, kind must be static. If specified,
3474 // iterations are divided into chunks of size chunk_size, chunks are
3475 // assigned to the teams of the league in a round-robin fashion in the
3476 // order of the team number. When no chunk_size is specified, the
3477 // iteration space is divided into chunks that are approximately equal
3478 // in size, and at most one chunk is distributed to each team of the
3479 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003480 bool StaticChunked = RT.isStaticChunked(
3481 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3482 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003483 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003484 /* Chunked */ Chunk != nullptr) ||
3485 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003486 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3487 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003488 CGOpenMPRuntime::StaticRTInput StaticInit(
3489 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003490 LB.getAddress(), UB.getAddress(), ST.getAddress(),
3491 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003492 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003493 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003494 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003495 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3496 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003497 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3498 ? S.getCombinedEnsureUpperBound()
3499 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003500 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003501 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3502 ? S.getCombinedInit()
3503 : S.getInit());
3504
Alexey Bataevddf3db92018-04-13 17:31:06 +00003505 const Expr *Cond =
3506 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3507 ? S.getCombinedCond()
3508 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003509
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003510 if (StaticChunked)
3511 Cond = S.getCombinedDistCond();
3512
3513 // For static unchunked schedules generate:
3514 //
3515 // 1. For distribute alone, codegen
3516 // while (idx <= UB) {
3517 // BODY;
3518 // ++idx;
3519 // }
3520 //
3521 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3522 // while (idx <= UB) {
3523 // <CodeGen rest of pragma>(LB, UB);
3524 // idx += ST;
3525 // }
3526 //
3527 // For static chunk one schedule generate:
3528 //
3529 // while (IV <= GlobalUB) {
3530 // <CodeGen rest of pragma>(LB, UB);
3531 // LB += ST;
3532 // UB += ST;
3533 // UB = min(UB, GlobalUB);
3534 // IV = LB;
3535 // }
3536 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003537 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3538 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3539 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003540 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003541 [&S, StaticChunked](CodeGenFunction &CGF) {
3542 if (StaticChunked) {
3543 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3544 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3545 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3546 CGF.EmitIgnoredExpr(S.getCombinedInit());
3547 }
3548 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003549 EmitBlock(LoopExit.getBlock());
3550 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003551 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003552 } else {
3553 // Emit the outer loop, which requests its work chunk [LB..UB] from
3554 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003555 const OMPLoopArguments LoopArguments = {
3556 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3557 Chunk};
3558 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3559 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003560 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003561 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003562 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003563 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003564 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003565 });
3566 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003567 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3568 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3569 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003570 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003571 // Emit post-update of the reduction variables if IsLastIter != 0.
3572 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003573 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003574 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003575 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003576 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003577 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003578 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003579 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003580 EmitOMPLastprivateClauseFinal(
3581 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003582 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003583 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003584 }
3585
3586 // We're now done with the loop, so jump to the continuation block.
3587 if (ContBlock) {
3588 EmitBranch(ContBlock);
3589 EmitBlock(ContBlock, true);
3590 }
3591 }
3592}
3593
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003594void CodeGenFunction::EmitOMPDistributeDirective(
3595 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003596 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003597 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003598 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003599 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003600 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003601}
3602
Alexey Bataev5f600d62015-09-29 03:48:57 +00003603static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3604 const CapturedStmt *S) {
3605 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3606 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3607 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003608 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003609 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003610 return Fn;
3611}
3612
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003613void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003614 if (S.hasClausesOfKind<OMPDependClause>()) {
3615 assert(!S.getAssociatedStmt() &&
3616 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003617 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3618 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003619 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003620 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003621 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003622 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3623 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003624 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003625 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003626 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3627 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003628 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003629 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003630 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003631 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003632 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003633 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003634 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003635 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003636 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003637 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003638}
3639
Alexey Bataevb57056f2015-01-22 06:17:56 +00003640static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003641 QualType SrcType, QualType DestType,
3642 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003643 assert(CGF.hasScalarEvaluationKind(DestType) &&
3644 "DestType must have scalar evaluation kind.");
3645 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003646 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3647 DestType, Loc)
3648 : CGF.EmitComplexToScalarConversion(
3649 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003650}
3651
3652static CodeGenFunction::ComplexPairTy
3653convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003654 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003655 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3656 "DestType must have complex evaluation kind.");
3657 CodeGenFunction::ComplexPairTy ComplexVal;
3658 if (Val.isScalar()) {
3659 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003660 QualType DestElementType =
3661 DestType->castAs<ComplexType>()->getElementType();
3662 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3663 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003664 ComplexVal = CodeGenFunction::ComplexPairTy(
3665 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3666 } else {
3667 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003668 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3669 QualType DestElementType =
3670 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003671 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003672 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003673 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003674 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003675 }
3676 return ComplexVal;
3677}
3678
Alexey Bataev5e018f92015-04-23 06:35:10 +00003679static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3680 LValue LVal, RValue RVal) {
3681 if (LVal.isGlobalReg()) {
3682 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3683 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003684 CGF.EmitAtomicStore(RVal, LVal,
3685 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3686 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003687 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003688 }
3689}
3690
Alexey Bataev8524d152016-01-21 12:35:58 +00003691void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3692 QualType RValTy, SourceLocation Loc) {
3693 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003694 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003695 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3696 *this, RVal, RValTy, LVal.getType(), Loc)),
3697 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003698 break;
3699 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003700 EmitStoreOfComplex(
3701 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003702 /*isInit=*/false);
3703 break;
3704 case TEK_Aggregate:
3705 llvm_unreachable("Must be a scalar or complex.");
3706 }
3707}
3708
Alexey Bataevddf3db92018-04-13 17:31:06 +00003709static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003710 const Expr *X, const Expr *V,
3711 SourceLocation Loc) {
3712 // v = x;
3713 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3714 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3715 LValue XLValue = CGF.EmitLValue(X);
3716 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003717 RValue Res = XLValue.isGlobalReg()
3718 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003719 : CGF.EmitAtomicLoad(
3720 XLValue, Loc,
3721 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3722 : llvm::AtomicOrdering::Monotonic,
3723 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003724 // OpenMP, 2.12.6, atomic Construct
3725 // Any atomic construct with a seq_cst clause forces the atomically
3726 // performed operation to include an implicit flush operation without a
3727 // list.
3728 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003729 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003730 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003731}
3732
Alexey Bataevddf3db92018-04-13 17:31:06 +00003733static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003734 const Expr *X, const Expr *E,
3735 SourceLocation Loc) {
3736 // x = expr;
3737 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003738 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003739 // OpenMP, 2.12.6, atomic Construct
3740 // Any atomic construct with a seq_cst clause forces the atomically
3741 // performed operation to include an implicit flush operation without a
3742 // list.
3743 if (IsSeqCst)
3744 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3745}
3746
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003747static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3748 RValue Update,
3749 BinaryOperatorKind BO,
3750 llvm::AtomicOrdering AO,
3751 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003752 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003753 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003754 // expression is simple and atomic is allowed for the given type for the
3755 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003756 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003757 !Update.getScalarVal()->getType()->isIntegerTy() ||
3758 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3759 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003760 X.getAddress().getElementType())) ||
3761 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003762 !Context.getTargetInfo().hasBuiltinAtomic(
3763 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003764 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003765
3766 llvm::AtomicRMWInst::BinOp RMWOp;
3767 switch (BO) {
3768 case BO_Add:
3769 RMWOp = llvm::AtomicRMWInst::Add;
3770 break;
3771 case BO_Sub:
3772 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003773 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003774 RMWOp = llvm::AtomicRMWInst::Sub;
3775 break;
3776 case BO_And:
3777 RMWOp = llvm::AtomicRMWInst::And;
3778 break;
3779 case BO_Or:
3780 RMWOp = llvm::AtomicRMWInst::Or;
3781 break;
3782 case BO_Xor:
3783 RMWOp = llvm::AtomicRMWInst::Xor;
3784 break;
3785 case BO_LT:
3786 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3787 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3788 : llvm::AtomicRMWInst::Max)
3789 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3790 : llvm::AtomicRMWInst::UMax);
3791 break;
3792 case BO_GT:
3793 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3794 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3795 : llvm::AtomicRMWInst::Min)
3796 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3797 : llvm::AtomicRMWInst::UMin);
3798 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003799 case BO_Assign:
3800 RMWOp = llvm::AtomicRMWInst::Xchg;
3801 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003802 case BO_Mul:
3803 case BO_Div:
3804 case BO_Rem:
3805 case BO_Shl:
3806 case BO_Shr:
3807 case BO_LAnd:
3808 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003809 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003810 case BO_PtrMemD:
3811 case BO_PtrMemI:
3812 case BO_LE:
3813 case BO_GE:
3814 case BO_EQ:
3815 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003816 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003817 case BO_AddAssign:
3818 case BO_SubAssign:
3819 case BO_AndAssign:
3820 case BO_OrAssign:
3821 case BO_XorAssign:
3822 case BO_MulAssign:
3823 case BO_DivAssign:
3824 case BO_RemAssign:
3825 case BO_ShlAssign:
3826 case BO_ShrAssign:
3827 case BO_Comma:
3828 llvm_unreachable("Unsupported atomic update operation");
3829 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003830 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003831 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3832 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003833 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003834 X.getType()->hasSignedIntegerRepresentation());
3835 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003836 llvm::Value *Res =
3837 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003838 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003839}
3840
Alexey Bataev5e018f92015-04-23 06:35:10 +00003841std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003842 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3843 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003844 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003845 // Update expressions are allowed to have the following forms:
3846 // x binop= expr; -> xrval + expr;
3847 // x++, ++x -> xrval + 1;
3848 // x--, --x -> xrval - 1;
3849 // x = x binop expr; -> xrval binop expr
3850 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003851 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3852 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003853 if (X.isGlobalReg()) {
3854 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3855 // 'xrval'.
3856 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3857 } else {
3858 // Perform compare-and-swap procedure.
3859 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003860 }
3861 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003862 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003863}
3864
Alexey Bataevddf3db92018-04-13 17:31:06 +00003865static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003866 const Expr *X, const Expr *E,
3867 const Expr *UE, bool IsXLHSInRHSPart,
3868 SourceLocation Loc) {
3869 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3870 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003871 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003872 // Update expressions are allowed to have the following forms:
3873 // x binop= expr; -> xrval + expr;
3874 // x++, ++x -> xrval + 1;
3875 // x--, --x -> xrval - 1;
3876 // x = x binop expr; -> xrval binop expr
3877 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003878 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003879 LValue XLValue = CGF.EmitLValue(X);
3880 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003881 llvm::AtomicOrdering AO = IsSeqCst
3882 ? llvm::AtomicOrdering::SequentiallyConsistent
3883 : llvm::AtomicOrdering::Monotonic;
3884 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3885 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3886 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3887 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3888 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3889 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3890 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3891 return CGF.EmitAnyExpr(UE);
3892 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003893 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3894 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3895 // OpenMP, 2.12.6, atomic Construct
3896 // Any atomic construct with a seq_cst clause forces the atomically
3897 // performed operation to include an implicit flush operation without a
3898 // list.
3899 if (IsSeqCst)
3900 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3901}
3902
3903static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003904 QualType SourceType, QualType ResType,
3905 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003906 switch (CGF.getEvaluationKind(ResType)) {
3907 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003908 return RValue::get(
3909 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003910 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003911 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003912 return RValue::getComplex(Res.first, Res.second);
3913 }
3914 case TEK_Aggregate:
3915 break;
3916 }
3917 llvm_unreachable("Must be a scalar or complex.");
3918}
3919
Alexey Bataevddf3db92018-04-13 17:31:06 +00003920static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003921 bool IsPostfixUpdate, const Expr *V,
3922 const Expr *X, const Expr *E,
3923 const Expr *UE, bool IsXLHSInRHSPart,
3924 SourceLocation Loc) {
3925 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3926 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3927 RValue NewVVal;
3928 LValue VLValue = CGF.EmitLValue(V);
3929 LValue XLValue = CGF.EmitLValue(X);
3930 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003931 llvm::AtomicOrdering AO = IsSeqCst
3932 ? llvm::AtomicOrdering::SequentiallyConsistent
3933 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003934 QualType NewVValType;
3935 if (UE) {
3936 // 'x' is updated with some additional value.
3937 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3938 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003939 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00003940 // Update expressions are allowed to have the following forms:
3941 // x binop= expr; -> xrval + expr;
3942 // x++, ++x -> xrval + 1;
3943 // x--, --x -> xrval - 1;
3944 // x = x binop expr; -> xrval binop expr
3945 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003946 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3947 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3948 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003949 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003950 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003951 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003952 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003953 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3954 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3955 RValue Res = CGF.EmitAnyExpr(UE);
3956 NewVVal = IsPostfixUpdate ? XRValue : Res;
3957 return Res;
3958 };
3959 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3960 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3961 if (Res.first) {
3962 // 'atomicrmw' instruction was generated.
3963 if (IsPostfixUpdate) {
3964 // Use old value from 'atomicrmw'.
3965 NewVVal = Res.second;
3966 } else {
3967 // 'atomicrmw' does not provide new value, so evaluate it using old
3968 // value of 'x'.
3969 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3970 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3971 NewVVal = CGF.EmitAnyExpr(UE);
3972 }
3973 }
3974 } else {
3975 // 'x' is simply rewritten with some 'expr'.
3976 NewVValType = X->getType().getNonReferenceType();
3977 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003978 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003979 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003980 NewVVal = XRValue;
3981 return ExprRValue;
3982 };
3983 // Try to perform atomicrmw xchg, otherwise simple exchange.
3984 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3985 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3986 Loc, Gen);
3987 if (Res.first) {
3988 // 'atomicrmw' instruction was generated.
3989 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3990 }
3991 }
3992 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003993 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003994 // OpenMP, 2.12.6, atomic Construct
3995 // Any atomic construct with a seq_cst clause forces the atomically
3996 // performed operation to include an implicit flush operation without a
3997 // list.
3998 if (IsSeqCst)
3999 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4000}
4001
Alexey Bataevddf3db92018-04-13 17:31:06 +00004002static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004003 bool IsSeqCst, bool IsPostfixUpdate,
4004 const Expr *X, const Expr *V, const Expr *E,
4005 const Expr *UE, bool IsXLHSInRHSPart,
4006 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004007 switch (Kind) {
4008 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004009 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004010 break;
4011 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004012 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004013 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004014 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004015 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004016 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004017 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004018 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004019 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004020 IsXLHSInRHSPart, Loc);
4021 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004022 case OMPC_if:
4023 case OMPC_final:
4024 case OMPC_num_threads:
4025 case OMPC_private:
4026 case OMPC_firstprivate:
4027 case OMPC_lastprivate:
4028 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004029 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004030 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004031 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004032 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004033 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004034 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004035 case OMPC_collapse:
4036 case OMPC_default:
4037 case OMPC_seq_cst:
4038 case OMPC_shared:
4039 case OMPC_linear:
4040 case OMPC_aligned:
4041 case OMPC_copyin:
4042 case OMPC_copyprivate:
4043 case OMPC_flush:
4044 case OMPC_proc_bind:
4045 case OMPC_schedule:
4046 case OMPC_ordered:
4047 case OMPC_nowait:
4048 case OMPC_untied:
4049 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004050 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004051 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004052 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004053 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004054 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004055 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004056 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004057 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004058 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004059 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004060 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004061 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004062 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004063 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004064 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004065 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004066 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004067 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004068 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004069 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004070 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004071 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004072 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004073 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004074 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004075 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004076 case OMPC_match:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004077 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4078 }
4079}
4080
4081void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004082 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004083 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004084 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004085 // Find first clause (skip seq_cst clause, if it is first).
4086 if (C->getClauseKind() != OMPC_seq_cst) {
4087 Kind = C->getClauseKind();
4088 break;
4089 }
4090 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004091
Alexey Bataevddf3db92018-04-13 17:31:06 +00004092 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004093 if (const auto *FE = dyn_cast<FullExpr>(CS))
4094 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004095 // Processing for statements under 'atomic capture'.
4096 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004097 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004098 if (const auto *FE = dyn_cast<FullExpr>(C))
4099 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004100 }
4101 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004102
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004103 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4104 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004105 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004106 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004107 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004108 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004109 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004110 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004111 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004112}
4113
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004114static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4115 const OMPExecutableDirective &S,
4116 const RegionCodeGenTy &CodeGen) {
4117 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4118 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004119
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004120 // On device emit this construct as inlined code.
4121 if (CGM.getLangOpts().OpenMPIsDevice) {
4122 OMPLexicalScope Scope(CGF, S, OMPD_target);
4123 CGM.getOpenMPRuntime().emitInlinedDirective(
4124 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004125 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004126 });
4127 return;
4128 }
4129
Samuel Antaoee8fb302016-01-06 13:42:12 +00004130 llvm::Function *Fn = nullptr;
4131 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004132
Samuel Antaobed3c462015-10-02 16:14:20 +00004133 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004134 // Check for the at most one if clause associated with the target region.
4135 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4136 if (C->getNameModifier() == OMPD_unknown ||
4137 C->getNameModifier() == OMPD_target) {
4138 IfCond = C->getCondition();
4139 break;
4140 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004141 }
4142
4143 // Check if we have any device clause associated with the directive.
4144 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004145 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004146 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004147
Samuel Antaoee8fb302016-01-06 13:42:12 +00004148 // Check if we have an if clause whose conditional always evaluates to false
4149 // or if we do not have any targets specified. If so the target region is not
4150 // an offload entry point.
4151 bool IsOffloadEntry = true;
4152 if (IfCond) {
4153 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004154 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004155 IsOffloadEntry = false;
4156 }
4157 if (CGM.getLangOpts().OMPTargetTriples.empty())
4158 IsOffloadEntry = false;
4159
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004160 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004161 StringRef ParentName;
4162 // In case we have Ctors/Dtors we use the complete type variant to produce
4163 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004164 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004166 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004167 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4168 else
4169 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004170 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004171
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004172 // Emit target region as a standalone region.
4173 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4174 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004175 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004176 auto &&SizeEmitter =
4177 [IsOffloadEntry](CodeGenFunction &CGF,
4178 const OMPLoopDirective &D) -> llvm::Value * {
4179 if (IsOffloadEntry) {
4180 OMPLoopScope(CGF, D);
4181 // Emit calculation of the iterations count.
4182 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4183 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4184 /*isSigned=*/false);
4185 return NumIterations;
4186 }
4187 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004188 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004189 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4190 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004191}
4192
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004193static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4194 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004195 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004196 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4197 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4198 CGF.EmitOMPPrivateClause(S, PrivateScope);
4199 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004200 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4201 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004202
Alexey Bataev475a7442018-01-12 19:39:11 +00004203 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004204}
4205
4206void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4207 StringRef ParentName,
4208 const OMPTargetDirective &S) {
4209 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4210 emitTargetRegion(CGF, S, Action);
4211 };
4212 llvm::Function *Fn;
4213 llvm::Constant *Addr;
4214 // Emit target region as a standalone region.
4215 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4216 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4217 assert(Fn && Addr && "Target device function emission failed.");
4218}
4219
4220void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4221 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4222 emitTargetRegion(CGF, S, Action);
4223 };
4224 emitCommonOMPTargetDirective(*this, S, CodeGen);
4225}
4226
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004227static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4228 const OMPExecutableDirective &S,
4229 OpenMPDirectiveKind InnermostKind,
4230 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004231 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004232 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004233 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4234 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004235
Alexey Bataevddf3db92018-04-13 17:31:06 +00004236 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4237 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004238 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004239 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4240 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004241
Carlo Bertollic6872252016-04-04 15:55:02 +00004242 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004243 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004244 }
4245
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004246 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004247 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4248 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004249 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004250 CapturedVars);
4251}
4252
4253void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004254 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004255 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004256 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004257 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004258 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4259 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004260 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004261 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004262 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004263 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004264 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004265 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004266 emitPostUpdateForReductionClause(*this, S,
4267 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004268}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004269
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004270static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4271 const OMPTargetTeamsDirective &S) {
4272 auto *CS = S.getCapturedStmt(OMPD_teams);
4273 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004274 // Emit teams region as a standalone region.
4275 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004276 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004277 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4278 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4279 CGF.EmitOMPPrivateClause(S, PrivateScope);
4280 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4281 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004282 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4283 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004284 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004285 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004286 };
4287 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004288 emitPostUpdateForReductionClause(CGF, S,
4289 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004290}
4291
4292void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4293 CodeGenModule &CGM, StringRef ParentName,
4294 const OMPTargetTeamsDirective &S) {
4295 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4296 emitTargetTeamsRegion(CGF, Action, S);
4297 };
4298 llvm::Function *Fn;
4299 llvm::Constant *Addr;
4300 // Emit target region as a standalone region.
4301 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4302 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4303 assert(Fn && Addr && "Target device function emission failed.");
4304}
4305
4306void CodeGenFunction::EmitOMPTargetTeamsDirective(
4307 const OMPTargetTeamsDirective &S) {
4308 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4309 emitTargetTeamsRegion(CGF, Action, S);
4310 };
4311 emitCommonOMPTargetDirective(*this, S, CodeGen);
4312}
4313
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004314static void
4315emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4316 const OMPTargetTeamsDistributeDirective &S) {
4317 Action.Enter(CGF);
4318 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4319 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4320 };
4321
4322 // Emit teams region as a standalone region.
4323 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004324 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004325 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004326 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4327 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4328 (void)PrivateScope.Privatize();
4329 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4330 CodeGenDistribute);
4331 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4332 };
4333 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4334 emitPostUpdateForReductionClause(CGF, S,
4335 [](CodeGenFunction &) { return nullptr; });
4336}
4337
4338void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4339 CodeGenModule &CGM, StringRef ParentName,
4340 const OMPTargetTeamsDistributeDirective &S) {
4341 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4342 emitTargetTeamsDistributeRegion(CGF, Action, S);
4343 };
4344 llvm::Function *Fn;
4345 llvm::Constant *Addr;
4346 // Emit target region as a standalone region.
4347 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4348 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4349 assert(Fn && Addr && "Target device function emission failed.");
4350}
4351
4352void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4353 const OMPTargetTeamsDistributeDirective &S) {
4354 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4355 emitTargetTeamsDistributeRegion(CGF, Action, S);
4356 };
4357 emitCommonOMPTargetDirective(*this, S, CodeGen);
4358}
4359
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004360static void emitTargetTeamsDistributeSimdRegion(
4361 CodeGenFunction &CGF, PrePostActionTy &Action,
4362 const OMPTargetTeamsDistributeSimdDirective &S) {
4363 Action.Enter(CGF);
4364 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4365 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4366 };
4367
4368 // Emit teams region as a standalone region.
4369 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004370 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004371 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004372 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4373 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4374 (void)PrivateScope.Privatize();
4375 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4376 CodeGenDistribute);
4377 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4378 };
4379 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4380 emitPostUpdateForReductionClause(CGF, S,
4381 [](CodeGenFunction &) { return nullptr; });
4382}
4383
4384void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4385 CodeGenModule &CGM, StringRef ParentName,
4386 const OMPTargetTeamsDistributeSimdDirective &S) {
4387 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4388 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4389 };
4390 llvm::Function *Fn;
4391 llvm::Constant *Addr;
4392 // Emit target region as a standalone region.
4393 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4394 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4395 assert(Fn && Addr && "Target device function emission failed.");
4396}
4397
4398void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4399 const OMPTargetTeamsDistributeSimdDirective &S) {
4400 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4401 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4402 };
4403 emitCommonOMPTargetDirective(*this, S, CodeGen);
4404}
4405
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004406void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4407 const OMPTeamsDistributeDirective &S) {
4408
4409 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4410 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4411 };
4412
4413 // Emit teams region as a standalone region.
4414 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004415 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004416 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004417 OMPPrivateScope PrivateScope(CGF);
4418 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4419 (void)PrivateScope.Privatize();
4420 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4421 CodeGenDistribute);
4422 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4423 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004424 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004425 emitPostUpdateForReductionClause(*this, S,
4426 [](CodeGenFunction &) { return nullptr; });
4427}
4428
Alexey Bataev999277a2017-12-06 14:31:09 +00004429void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4430 const OMPTeamsDistributeSimdDirective &S) {
4431 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4432 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4433 };
4434
4435 // Emit teams region as a standalone region.
4436 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004437 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004438 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004439 OMPPrivateScope PrivateScope(CGF);
4440 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4441 (void)PrivateScope.Privatize();
4442 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4443 CodeGenDistribute);
4444 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4445 };
4446 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4447 emitPostUpdateForReductionClause(*this, S,
4448 [](CodeGenFunction &) { return nullptr; });
4449}
4450
Carlo Bertolli62fae152017-11-20 20:46:39 +00004451void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4452 const OMPTeamsDistributeParallelForDirective &S) {
4453 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4454 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4455 S.getDistInc());
4456 };
4457
4458 // Emit teams region as a standalone region.
4459 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004460 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004461 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004462 OMPPrivateScope PrivateScope(CGF);
4463 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4464 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004465 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4466 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004467 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4468 };
4469 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4470 emitPostUpdateForReductionClause(*this, S,
4471 [](CodeGenFunction &) { return nullptr; });
4472}
4473
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004474void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4475 const OMPTeamsDistributeParallelForSimdDirective &S) {
4476 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4477 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4478 S.getDistInc());
4479 };
4480
4481 // Emit teams region as a standalone region.
4482 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004483 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004484 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004485 OMPPrivateScope PrivateScope(CGF);
4486 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4487 (void)PrivateScope.Privatize();
4488 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4489 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4490 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4491 };
4492 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4493 emitPostUpdateForReductionClause(*this, S,
4494 [](CodeGenFunction &) { return nullptr; });
4495}
4496
Carlo Bertolli52978c32018-01-03 21:12:44 +00004497static void emitTargetTeamsDistributeParallelForRegion(
4498 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4499 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004500 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004501 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4502 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4503 S.getDistInc());
4504 };
4505
4506 // Emit teams region as a standalone region.
4507 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004508 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004509 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004510 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4511 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4512 (void)PrivateScope.Privatize();
4513 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4514 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4515 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4516 };
4517
4518 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4519 CodeGenTeams);
4520 emitPostUpdateForReductionClause(CGF, S,
4521 [](CodeGenFunction &) { return nullptr; });
4522}
4523
4524void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4525 CodeGenModule &CGM, StringRef ParentName,
4526 const OMPTargetTeamsDistributeParallelForDirective &S) {
4527 // Emit SPMD target teams distribute parallel for region as a standalone
4528 // region.
4529 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4530 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4531 };
4532 llvm::Function *Fn;
4533 llvm::Constant *Addr;
4534 // Emit target region as a standalone region.
4535 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4536 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4537 assert(Fn && Addr && "Target device function emission failed.");
4538}
4539
4540void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4541 const OMPTargetTeamsDistributeParallelForDirective &S) {
4542 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4543 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4544 };
4545 emitCommonOMPTargetDirective(*this, S, CodeGen);
4546}
4547
Alexey Bataev647dd842018-01-15 20:59:40 +00004548static void emitTargetTeamsDistributeParallelForSimdRegion(
4549 CodeGenFunction &CGF,
4550 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4551 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004552 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004553 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4554 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4555 S.getDistInc());
4556 };
4557
4558 // Emit teams region as a standalone region.
4559 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004560 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004561 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004562 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4563 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4564 (void)PrivateScope.Privatize();
4565 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4566 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4567 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4568 };
4569
4570 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4571 CodeGenTeams);
4572 emitPostUpdateForReductionClause(CGF, S,
4573 [](CodeGenFunction &) { return nullptr; });
4574}
4575
4576void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4577 CodeGenModule &CGM, StringRef ParentName,
4578 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4579 // Emit SPMD target teams distribute parallel for simd region as a standalone
4580 // region.
4581 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4582 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4583 };
4584 llvm::Function *Fn;
4585 llvm::Constant *Addr;
4586 // Emit target region as a standalone region.
4587 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4588 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4589 assert(Fn && Addr && "Target device function emission failed.");
4590}
4591
4592void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4593 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4594 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4595 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4596 };
4597 emitCommonOMPTargetDirective(*this, S, CodeGen);
4598}
4599
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004600void CodeGenFunction::EmitOMPCancellationPointDirective(
4601 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004602 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004603 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004604}
4605
Alexey Bataev80909872015-07-02 11:25:17 +00004606void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004607 const Expr *IfCond = nullptr;
4608 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4609 if (C->getNameModifier() == OMPD_unknown ||
4610 C->getNameModifier() == OMPD_cancel) {
4611 IfCond = C->getCondition();
4612 break;
4613 }
4614 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004615 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004616 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004617}
4618
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004619CodeGenFunction::JumpDest
4620CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004621 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4622 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004623 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004624 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004625 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4626 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004627 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004628 Kind == OMPD_teams_distribute_parallel_for ||
4629 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004630 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004631}
Michael Wong65f367f2015-07-21 13:44:28 +00004632
Samuel Antaocc10b852016-07-28 14:23:26 +00004633void CodeGenFunction::EmitOMPUseDevicePtrClause(
4634 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4635 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4636 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4637 auto OrigVarIt = C.varlist_begin();
4638 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004639 for (const Expr *PvtVarIt : C.private_copies()) {
4640 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4641 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4642 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004643
4644 // In order to identify the right initializer we need to match the
4645 // declaration used by the mapping logic. In some cases we may get
4646 // OMPCapturedExprDecl that refers to the original declaration.
4647 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004648 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004649 // OMPCapturedExprDecl are used to privative fields of the current
4650 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004651 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004652 assert(isa<CXXThisExpr>(ME->getBase()) &&
4653 "Base should be the current struct!");
4654 MatchingVD = ME->getMemberDecl();
4655 }
4656
4657 // If we don't have information about the current list item, move on to
4658 // the next one.
4659 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4660 if (InitAddrIt == CaptureDeviceAddrMap.end())
4661 continue;
4662
Alexey Bataevddf3db92018-04-13 17:31:06 +00004663 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4664 InitAddrIt, InitVD,
4665 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004666 // Initialize the temporary initialization variable with the address we
4667 // get from the runtime library. We have to cast the source address
4668 // because it is always a void *. References are materialized in the
4669 // privatization scope, so the initialization here disregards the fact
4670 // the original variable is a reference.
4671 QualType AddrQTy =
4672 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4673 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4674 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4675 setAddrOfLocalVar(InitVD, InitAddr);
4676
4677 // Emit private declaration, it will be initialized by the value we
4678 // declaration we just added to the local declarations map.
4679 EmitDecl(*PvtVD);
4680
4681 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004682 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004683 LocalDeclMap.erase(InitVD);
4684
4685 // Return the address of the private variable.
4686 return GetAddrOfLocalVar(PvtVD);
4687 });
4688 assert(IsRegistered && "firstprivate var already registered as private");
4689 // Silence the warning about unused variable.
4690 (void)IsRegistered;
4691
4692 ++OrigVarIt;
4693 ++InitIt;
4694 }
4695}
4696
Michael Wong65f367f2015-07-21 13:44:28 +00004697// Generate the instructions for '#pragma omp target data' directive.
4698void CodeGenFunction::EmitOMPTargetDataDirective(
4699 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004700 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4701
4702 // Create a pre/post action to signal the privatization of the device pointer.
4703 // This action can be replaced by the OpenMP runtime code generation to
4704 // deactivate privatization.
4705 bool PrivatizeDevicePointers = false;
4706 class DevicePointerPrivActionTy : public PrePostActionTy {
4707 bool &PrivatizeDevicePointers;
4708
4709 public:
4710 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4711 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4712 void Enter(CodeGenFunction &CGF) override {
4713 PrivatizeDevicePointers = true;
4714 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004715 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004716 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4717
4718 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004719 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004720 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004721 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004722 };
4723
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004724 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004725 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4726 &InnermostCodeGen](CodeGenFunction &CGF,
4727 PrePostActionTy &Action) {
4728 RegionCodeGenTy RCG(InnermostCodeGen);
4729 PrivatizeDevicePointers = false;
4730
4731 // Call the pre-action to change the status of PrivatizeDevicePointers if
4732 // needed.
4733 Action.Enter(CGF);
4734
4735 if (PrivatizeDevicePointers) {
4736 OMPPrivateScope PrivateScope(CGF);
4737 // Emit all instances of the use_device_ptr clause.
4738 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4739 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4740 Info.CaptureDeviceAddrMap);
4741 (void)PrivateScope.Privatize();
4742 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004743 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004744 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004745 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004746 };
4747
4748 // Forward the provided action to the privatization codegen.
4749 RegionCodeGenTy PrivRCG(PrivCodeGen);
4750 PrivRCG.setAction(Action);
4751
4752 // Notwithstanding the body of the region is emitted as inlined directive,
4753 // we don't use an inline scope as changes in the references inside the
4754 // region are expected to be visible outside, so we do not privative them.
4755 OMPLexicalScope Scope(CGF, S);
4756 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4757 PrivRCG);
4758 };
4759
4760 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004761
4762 // If we don't have target devices, don't bother emitting the data mapping
4763 // code.
4764 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004765 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004766 return;
4767 }
4768
4769 // Check if we have any if clause associated with the directive.
4770 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004771 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004772 IfCond = C->getCondition();
4773
4774 // Check if we have any device clause associated with the directive.
4775 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004776 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004777 Device = C->getDevice();
4778
Samuel Antaocc10b852016-07-28 14:23:26 +00004779 // Set the action to signal privatization of device pointers.
4780 RCG.setAction(PrivAction);
4781
4782 // Emit region code.
4783 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4784 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004785}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004786
Samuel Antaodf67fc42016-01-19 19:15:56 +00004787void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4788 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004789 // If we don't have target devices, don't bother emitting the data mapping
4790 // code.
4791 if (CGM.getLangOpts().OMPTargetTriples.empty())
4792 return;
4793
4794 // Check if we have any if clause associated with the directive.
4795 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004796 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004797 IfCond = C->getCondition();
4798
4799 // Check if we have any device clause associated with the directive.
4800 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004801 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004802 Device = C->getDevice();
4803
Alexey Bataev475a7442018-01-12 19:39:11 +00004804 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004805 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004806}
4807
Samuel Antao72590762016-01-19 20:04:50 +00004808void CodeGenFunction::EmitOMPTargetExitDataDirective(
4809 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004810 // If we don't have target devices, don't bother emitting the data mapping
4811 // code.
4812 if (CGM.getLangOpts().OMPTargetTriples.empty())
4813 return;
4814
4815 // Check if we have any if clause associated with the directive.
4816 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004817 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004818 IfCond = C->getCondition();
4819
4820 // Check if we have any device clause associated with the directive.
4821 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004822 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004823 Device = C->getDevice();
4824
Alexey Bataev475a7442018-01-12 19:39:11 +00004825 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004826 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004827}
4828
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004829static void emitTargetParallelRegion(CodeGenFunction &CGF,
4830 const OMPTargetParallelDirective &S,
4831 PrePostActionTy &Action) {
4832 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004833 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004834 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004835 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004836 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004837 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4838 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4839 CGF.EmitOMPPrivateClause(S, PrivateScope);
4840 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4841 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004842 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4843 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004844 // TODO: Add support for clauses.
4845 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004846 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004847 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004848 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4849 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004850 emitPostUpdateForReductionClause(CGF, S,
4851 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004852}
4853
4854void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4855 CodeGenModule &CGM, StringRef ParentName,
4856 const OMPTargetParallelDirective &S) {
4857 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4858 emitTargetParallelRegion(CGF, S, Action);
4859 };
4860 llvm::Function *Fn;
4861 llvm::Constant *Addr;
4862 // Emit target region as a standalone region.
4863 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4864 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4865 assert(Fn && Addr && "Target device function emission failed.");
4866}
4867
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004868void CodeGenFunction::EmitOMPTargetParallelDirective(
4869 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004870 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4871 emitTargetParallelRegion(CGF, S, Action);
4872 };
4873 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004874}
4875
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004876static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4877 const OMPTargetParallelForDirective &S,
4878 PrePostActionTy &Action) {
4879 Action.Enter(CGF);
4880 // Emit directive as a combined directive that consists of two implicit
4881 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004882 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4883 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004884 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4885 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004886 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4887 emitDispatchForLoopBounds);
4888 };
4889 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4890 emitEmptyBoundParameters);
4891}
4892
4893void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4894 CodeGenModule &CGM, StringRef ParentName,
4895 const OMPTargetParallelForDirective &S) {
4896 // Emit SPMD target parallel for region as a standalone region.
4897 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4898 emitTargetParallelForRegion(CGF, S, Action);
4899 };
4900 llvm::Function *Fn;
4901 llvm::Constant *Addr;
4902 // Emit target region as a standalone region.
4903 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4904 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4905 assert(Fn && Addr && "Target device function emission failed.");
4906}
4907
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004908void CodeGenFunction::EmitOMPTargetParallelForDirective(
4909 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004910 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4911 emitTargetParallelForRegion(CGF, S, Action);
4912 };
4913 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004914}
4915
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004916static void
4917emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4918 const OMPTargetParallelForSimdDirective &S,
4919 PrePostActionTy &Action) {
4920 Action.Enter(CGF);
4921 // Emit directive as a combined directive that consists of two implicit
4922 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004923 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4924 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004925 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4926 emitDispatchForLoopBounds);
4927 };
4928 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4929 emitEmptyBoundParameters);
4930}
4931
4932void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4933 CodeGenModule &CGM, StringRef ParentName,
4934 const OMPTargetParallelForSimdDirective &S) {
4935 // Emit SPMD target parallel for region as a standalone region.
4936 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4937 emitTargetParallelForSimdRegion(CGF, S, Action);
4938 };
4939 llvm::Function *Fn;
4940 llvm::Constant *Addr;
4941 // Emit target region as a standalone region.
4942 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4943 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4944 assert(Fn && Addr && "Target device function emission failed.");
4945}
4946
4947void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4948 const OMPTargetParallelForSimdDirective &S) {
4949 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4950 emitTargetParallelForSimdRegion(CGF, S, Action);
4951 };
4952 emitCommonOMPTargetDirective(*this, S, CodeGen);
4953}
4954
Alexey Bataev7292c292016-04-25 12:22:29 +00004955/// Emit a helper variable and return corresponding lvalue.
4956static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4957 const ImplicitParamDecl *PVD,
4958 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004959 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
4960 Privates.addPrivate(VDecl,
4961 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00004962}
4963
4964void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4965 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4966 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004967 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004968 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4969 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004970 const Expr *IfCond = nullptr;
4971 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4972 if (C->getNameModifier() == OMPD_unknown ||
4973 C->getNameModifier() == OMPD_taskloop) {
4974 IfCond = C->getCondition();
4975 break;
4976 }
4977 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004978
4979 OMPTaskDataTy Data;
4980 // Check if taskloop must be emitted without taskgroup.
4981 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004982 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004983 Data.Tied = true;
4984 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004985 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4986 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004987 Data.Schedule.setInt(/*IntVal=*/false);
4988 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004989 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4990 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004991 Data.Schedule.setInt(/*IntVal=*/true);
4992 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004993 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004994
4995 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4996 // if (PreCond) {
4997 // for (IV in 0..LastIteration) BODY;
4998 // <Final counter/linear vars updates>;
4999 // }
5000 //
5001
5002 // Emit: if (PreCond) - begin.
5003 // If the condition constant folds and can be elided, avoid emitting the
5004 // whole loop.
5005 bool CondConstant;
5006 llvm::BasicBlock *ContBlock = nullptr;
5007 OMPLoopScope PreInitScope(CGF, S);
5008 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5009 if (!CondConstant)
5010 return;
5011 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005012 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005013 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5014 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5015 CGF.getProfileCount(&S));
5016 CGF.EmitBlock(ThenBlock);
5017 CGF.incrementProfileCounter(&S);
5018 }
5019
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005020 if (isOpenMPSimdDirective(S.getDirectiveKind()))
5021 CGF.EmitOMPSimdInit(S);
5022
Alexey Bataev7292c292016-04-25 12:22:29 +00005023 OMPPrivateScope LoopScope(CGF);
5024 // Emit helper vars inits.
5025 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5026 auto *I = CS->getCapturedDecl()->param_begin();
5027 auto *LBP = std::next(I, LowerBound);
5028 auto *UBP = std::next(I, UpperBound);
5029 auto *STP = std::next(I, Stride);
5030 auto *LIP = std::next(I, LastIter);
5031 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5032 LoopScope);
5033 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5034 LoopScope);
5035 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5036 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5037 LoopScope);
5038 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005039 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005040 (void)LoopScope.Privatize();
5041 // Emit the loop iteration variable.
5042 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005043 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005044 CGF.EmitVarDecl(*IVDecl);
5045 CGF.EmitIgnoredExpr(S.getInit());
5046
5047 // Emit the iterations count variable.
5048 // If it is not a variable, Sema decided to calculate iterations count on
5049 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005050 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005051 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5052 // Emit calculation of the iterations count.
5053 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5054 }
5055
5056 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
5057 S.getInc(),
5058 [&S](CodeGenFunction &CGF) {
5059 CGF.EmitOMPLoopBody(S, JumpDest());
5060 CGF.EmitStopPoint(&S);
5061 },
5062 [](CodeGenFunction &) {});
5063 // Emit: if (PreCond) - end.
5064 if (ContBlock) {
5065 CGF.EmitBranch(ContBlock);
5066 CGF.EmitBlock(ContBlock, true);
5067 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005068 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5069 if (HasLastprivateClause) {
5070 CGF.EmitOMPLastprivateClauseFinal(
5071 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5072 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5073 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005074 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005075 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005076 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005077 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005078 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005079 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005080 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5081 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005082 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005083 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005084 OutlinedFn, SharedsTy,
5085 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005086 };
5087 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5088 CodeGen);
5089 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005090 if (Data.Nogroup) {
5091 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5092 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005093 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5094 *this,
5095 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5096 PrePostActionTy &Action) {
5097 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005098 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5099 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005100 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005101 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005102 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005103}
5104
Alexey Bataev49f6e782015-12-01 04:18:41 +00005105void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005106 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005107}
5108
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005109void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5110 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005111 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005112}
Samuel Antao686c70c2016-05-26 17:30:50 +00005113
Alexey Bataev60e51c42019-10-10 20:13:02 +00005114void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5115 const OMPMasterTaskLoopDirective &S) {
5116 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5117 Action.Enter(CGF);
5118 EmitOMPTaskLoopBasedDirective(S);
5119 };
5120 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5121 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5122}
5123
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005124void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5125 const OMPParallelMasterTaskLoopDirective &S) {
5126 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5127 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5128 PrePostActionTy &Action) {
5129 Action.Enter(CGF);
5130 CGF.EmitOMPTaskLoopBasedDirective(S);
5131 };
5132 OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5133 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5134 S.getBeginLoc());
5135 };
5136 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5137 emitEmptyBoundParameters);
5138}
5139
Samuel Antao686c70c2016-05-26 17:30:50 +00005140// Generate the instructions for '#pragma omp target update' directive.
5141void CodeGenFunction::EmitOMPTargetUpdateDirective(
5142 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005143 // If we don't have target devices, don't bother emitting the data mapping
5144 // code.
5145 if (CGM.getLangOpts().OMPTargetTriples.empty())
5146 return;
5147
5148 // Check if we have any if clause associated with the directive.
5149 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005150 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005151 IfCond = C->getCondition();
5152
5153 // Check if we have any device clause associated with the directive.
5154 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005155 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005156 Device = C->getDevice();
5157
Alexey Bataev475a7442018-01-12 19:39:11 +00005158 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005159 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005160}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005161
5162void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5163 const OMPExecutableDirective &D) {
5164 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5165 return;
5166 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5167 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5168 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5169 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005170 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005171 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005172 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005173 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5174 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5175 LValue GlobLVal = CGF.EmitLValue(E);
5176 LoopGlobals.addPrivate(
5177 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
5178 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005179 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005180 // Emit only those that were not explicitly referenced in clauses.
5181 if (!CGF.LocalDeclMap.count(VD))
5182 CGF.EmitVarDecl(*VD);
5183 }
5184 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005185 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5186 if (!C->getNumForLoops())
5187 continue;
5188 for (unsigned I = LD->getCollapsedNumber(),
5189 E = C->getLoopNumIterations().size();
5190 I < E; ++I) {
5191 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005192 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005193 // Emit only those that were not explicitly referenced in clauses.
5194 if (!CGF.LocalDeclMap.count(VD))
5195 CGF.EmitVarDecl(*VD);
5196 }
5197 }
5198 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005199 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005200 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005201 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005202 }
5203 };
5204 OMPSimdLexicalScope Scope(*this, D);
5205 CGM.getOpenMPRuntime().emitInlinedDirective(
5206 *this,
5207 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5208 : D.getDirectiveKind(),
5209 CodeGen);
5210}