blob: b315421d51f39f2e28364bb080ad3dce6cb9de5e [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 Bataev61205822019-12-04 09:50:21 -050018#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080019#include "clang/AST/Attr.h"
20#include "clang/AST/DeclOpenMP.h"
Alexey Bataeve6d25832020-01-27 14:10:17 -050021#include "clang/AST/OpenMPClause.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "clang/AST/Stmt.h"
23#include "clang/AST/StmtOpenMP.h"
Alexey Bataevea9166b2020-02-06 16:30:23 -050024#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev8bbf2e32019-11-04 09:59:11 -050025#include "clang/Basic/PrettyStackTrace.h"
Johannes Doerfert10fedd92019-12-26 11:23:38 -060026#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027using namespace clang;
28using namespace CodeGen;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060029using namespace llvm::omp;
Alexey Bataev9959db52014-05-06 10:08:46 +000030
Alexey Bataev3392d762016-02-16 11:18:12 +000031namespace {
32/// Lexical scope for OpenMP executable constructs, that handles correct codegen
33/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000034class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000035 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
36 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000037 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
38 if (const auto *PreInit =
39 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000040 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000041 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000042 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000043 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000044 CodeGenFunction::AutoVarEmission Emission =
45 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
46 CGF.EmitAutoVarCleanups(Emission);
47 }
48 }
Alexey Bataev3392d762016-02-16 11:18:12 +000049 }
50 }
51 }
52 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000053 CodeGenFunction::OMPPrivateScope InlinedShareds;
54
55 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
56 return CGF.LambdaCaptureFields.lookup(VD) ||
57 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
58 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
59 }
Alexey Bataev3392d762016-02-16 11:18:12 +000060
Alexey Bataev3392d762016-02-16 11:18:12 +000061public:
Alexey Bataev475a7442018-01-12 19:39:11 +000062 OMPLexicalScope(
63 CodeGenFunction &CGF, const OMPExecutableDirective &S,
64 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
65 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000066 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
67 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000068 if (EmitPreInitStmt)
69 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000070 if (!CapturedRegion.hasValue())
71 return;
72 assert(S.hasAssociatedStmt() &&
73 "Expected associated statement for inlined directive.");
74 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000075 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000076 if (C.capturesVariable() || C.capturesVariableByCopy()) {
77 auto *VD = C.getCapturedVar();
78 assert(VD == VD->getCanonicalDecl() &&
79 "Canonical decl must be captured.");
80 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000081 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000082 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
83 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000084 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000085 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanakaf139ae32019-12-03 15:17:01 -080086 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +000087 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000088 }
89 }
Alexey Bataev475a7442018-01-12 19:39:11 +000090 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000091 }
92};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000093
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094/// Lexical scope for OpenMP parallel construct, that handles correct codegen
95/// for captured expressions.
96class OMPParallelScope final : public OMPLexicalScope {
97 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
98 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000099 return !(isOpenMPTargetExecutionDirective(Kind) ||
100 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000101 isOpenMPParallelDirective(Kind);
102 }
103
104public:
105 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000106 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
107 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000108};
109
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000110/// Lexical scope for OpenMP teams construct, that handles correct codegen
111/// for captured expressions.
112class OMPTeamsScope final : public OMPLexicalScope {
113 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
114 OpenMPDirectiveKind Kind = S.getDirectiveKind();
115 return !isOpenMPTargetExecutionDirective(Kind) &&
116 isOpenMPTeamsDirective(Kind);
117 }
118
119public:
120 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000121 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
122 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000123};
124
Alexey Bataev5a3af132016-03-29 08:58:54 +0000125/// Private scope for OpenMP loop-based directives, that supports capturing
126/// of used expression from loop statement.
127class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
128 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000129 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevf71939c2019-09-18 19:24:07 +0000130 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000131 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000132 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf71939c2019-09-18 19:24:07 +0000133 EmittedAsPrivate.insert(VD->getCanonicalDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000134 (void)PreCondVars.setVarAddr(
135 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000136 }
Alexey Bataevf71939c2019-09-18 19:24:07 +0000137 // Mark private vars as undefs.
138 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
139 for (const Expr *IRef : C->varlists()) {
140 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
141 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
142 (void)PreCondVars.setVarAddr(
143 CGF, OrigVD,
144 Address(llvm::UndefValue::get(
145 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
146 OrigVD->getType().getNonReferenceType()))),
147 CGF.getContext().getDeclAlign(OrigVD)));
148 }
149 }
150 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000151 (void)PreCondVars.apply(CGF);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000152 // Emit init, __range and __end variables for C++ range loops.
153 const Stmt *Body =
154 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
155 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
Alexey Bataev8bbf2e32019-11-04 09:59:11 -0500156 Body = OMPLoopDirective::tryToFindNextInnerLoop(
157 Body, /*TryImperfectlyNestedLoops=*/true);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000158 if (auto *For = dyn_cast<ForStmt>(Body)) {
159 Body = For->getBody();
160 } else {
161 assert(isa<CXXForRangeStmt>(Body) &&
Alexey Bataevd457f7e2019-10-07 19:57:40 +0000162 "Expected canonical for loop or range-based for loop.");
Alexey Bataevbef93a92019-10-07 18:54:57 +0000163 auto *CXXFor = cast<CXXForRangeStmt>(Body);
164 if (const Stmt *Init = CXXFor->getInit())
165 CGF.EmitStmt(Init);
166 CGF.EmitStmt(CXXFor->getRangeStmt());
167 CGF.EmitStmt(CXXFor->getEndStmt());
168 Body = CXXFor->getBody();
169 }
170 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000171 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000172 for (const auto *I : PreInits->decls())
173 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000174 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000175 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000176 }
177
178public:
179 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
180 : CodeGenFunction::RunCleanupsScope(CGF) {
181 emitPreInitStmt(CGF, S);
182 }
183};
184
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000185class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
186 CodeGenFunction::OMPPrivateScope InlinedShareds;
187
188 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
189 return CGF.LambdaCaptureFields.lookup(VD) ||
190 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
191 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
192 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
193 }
194
195public:
196 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
197 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
198 InlinedShareds(CGF) {
199 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000200 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
201 if (const auto *PreInit =
202 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000203 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000204 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000205 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000206 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000207 CodeGenFunction::AutoVarEmission Emission =
208 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
209 CGF.EmitAutoVarCleanups(Emission);
210 }
211 }
212 }
213 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
214 for (const Expr *E : UDP->varlists()) {
215 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
216 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
217 CGF.EmitVarDecl(*OED);
218 }
219 }
220 }
221 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
222 CGF.EmitOMPPrivateClause(S, InlinedShareds);
223 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
224 if (const Expr *E = TG->getReductionRef())
225 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
226 }
227 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
228 while (CS) {
229 for (auto &C : CS->captures()) {
230 if (C.capturesVariable() || C.capturesVariableByCopy()) {
231 auto *VD = C.getCapturedVar();
232 assert(VD == VD->getCanonicalDecl() &&
233 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000234 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000235 isCapturedVar(CGF, VD) ||
236 (CGF.CapturedStmtInfo &&
237 InlinedShareds.isGlobalVarCaptured(VD)),
238 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000239 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000240 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800241 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000242 });
243 }
244 }
245 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
246 }
247 (void)InlinedShareds.Privatize();
248 }
249};
250
Alexey Bataev3392d762016-02-16 11:18:12 +0000251} // namespace
252
Alexey Bataevf8365372017-11-17 17:57:25 +0000253static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
254 const OMPExecutableDirective &S,
255 const RegionCodeGenTy &CodeGen);
256
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000257LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000258 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
259 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000260 OrigVD = OrigVD->getCanonicalDecl();
261 bool IsCaptured =
262 LambdaCaptureFields.lookup(OrigVD) ||
263 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
264 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000265 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000266 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
267 return EmitLValue(&DRE);
268 }
269 }
270 return EmitLValue(E);
271}
272
Alexey Bataev1189bd02016-01-26 12:20:39 +0000273llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000274 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000275 llvm::Value *Size = nullptr;
276 auto SizeInChars = C.getTypeSizeInChars(Ty);
277 if (SizeInChars.isZero()) {
278 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000279 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
280 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000281 Ty = VlaSize.Type;
282 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
283 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000284 }
285 SizeInChars = C.getTypeSizeInChars(Ty);
286 if (SizeInChars.isZero())
287 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000288 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
289 }
290 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000291}
292
Alexey Bataev2377fe92015-09-10 08:12:02 +0000293void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 const RecordDecl *RD = S.getCapturedRecordDecl();
296 auto CurField = RD->field_begin();
297 auto CurCap = S.captures().begin();
298 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
299 E = S.capture_init_end();
300 I != E; ++I, ++CurField, ++CurCap) {
301 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000302 const VariableArrayType *VAT = CurField->getCapturedVLAType();
303 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000304 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000305 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000306 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000307 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000308 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000309
310 // If the field is not a pointer, we need to save the actual value
311 // and load it as a void pointer.
312 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000313 ASTContext &Ctx = getContext();
314 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000315 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000316 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000317 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
318
Alexey Bataevddf3db92018-04-13 17:31:06 +0000319 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000320 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000321 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000322 LValue SrcLV =
323 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
324
325 // Store the value using the source type pointer.
326 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
327
328 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000329 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000330 }
331 CapturedVars.push_back(CV);
332 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000333 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800334 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000335 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000336 }
337}
338
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000339static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
340 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000341 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000342 ASTContext &Ctx = CGF.getContext();
343
Alexey Bataevddf3db92018-04-13 17:31:06 +0000344 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800345 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000346 Ctx.getPointerType(DstType), Loc);
347 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000348 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800349 .getAddress(CGF);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000350 return TmpAddr;
351}
352
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000353static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000354 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000355 return C.getLValueReferenceType(
356 getCanonicalParamType(C, T.getNonReferenceType()),
357 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000358 if (T->isPointerType())
359 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000360 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
361 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000362 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000363 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000364 return C.getCanonicalType(T);
365 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000366 return C.getCanonicalParamType(T);
367}
368
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000369namespace {
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500370/// Contains required data for proper outlined function codegen.
371struct FunctionOptions {
372 /// Captured statement for which the function is generated.
373 const CapturedStmt *S = nullptr;
374 /// true if cast to/from UIntPtr is required for variables captured by
375 /// value.
376 const bool UIntPtrCastRequired = true;
377 /// true if only casted arguments must be registered as local args or VLA
378 /// sizes.
379 const bool RegisterCastedArgsOnly = false;
380 /// Name of the generated function.
381 const StringRef FunctionName;
382 /// Location of the non-debug version of the outlined function.
383 SourceLocation Loc;
384 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
385 bool RegisterCastedArgsOnly, StringRef FunctionName,
386 SourceLocation Loc)
387 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
388 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
389 FunctionName(FunctionName), Loc(Loc) {}
390};
391} // namespace
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000392
Alexey Bataeve754b182017-08-09 19:38:53 +0000393static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000394 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000395 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000396 &LocalAddrs,
397 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
398 &VLASizes,
399 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
400 const CapturedDecl *CD = FO.S->getCapturedDecl();
401 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000402 assert(CD->hasBody() && "missing CapturedDecl body");
403
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000404 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000405 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000406 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000407 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000408 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000409 Args.append(CD->param_begin(),
410 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000411 TargetArgs.append(
412 CD->param_begin(),
413 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000414 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000415 FunctionDecl *DebugFunctionDecl = nullptr;
416 if (!FO.UIntPtrCastRequired) {
417 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000418 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000419 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000420 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000421 SourceLocation(), DeclarationName(), FunctionTy,
422 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
423 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000424 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000425 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000426 QualType ArgType = FD->getType();
427 IdentifierInfo *II = nullptr;
428 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000429
430 // If this is a capture by copy and the type is not a pointer, the outlined
431 // function argument type should be uintptr and the value properly casted to
432 // uintptr. This is necessary given that the runtime library is only able to
433 // deal with pointers. We can pass in the same way the VLA type sizes to the
434 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000435 if (FO.UIntPtrCastRequired &&
436 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
437 I->capturesVariableArrayType()))
438 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000439
440 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 CapVar = I->getCapturedVar();
442 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000443 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000444 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000445 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000446 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000447 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000448 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000449 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000450 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000451 VarDecl *Arg;
452 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
453 Arg = ParmVarDecl::Create(
454 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000455 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000456 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
457 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
458 } else {
459 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
460 II, ArgType, ImplicitParamDecl::Other);
461 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000462 Args.emplace_back(Arg);
463 // Do not cast arguments if we emit function with non-original types.
464 TargetArgs.emplace_back(
465 FO.UIntPtrCastRequired
466 ? Arg
467 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000468 ++I;
469 }
470 Args.append(
471 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
472 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000473 TargetArgs.append(
474 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
475 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000476
477 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000478 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000479 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000480 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
481
Alexey Bataevddf3db92018-04-13 17:31:06 +0000482 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000483 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
484 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000485 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
486 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000487 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000488 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000489
490 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000491 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500492 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
493 FO.UIntPtrCastRequired ? FO.Loc
494 : CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000495 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000496 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000497 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000498 // Do not map arguments if we emit function with non-original types.
499 Address LocalAddr(Address::invalid());
500 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
501 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
502 TargetArgs[Cnt]);
503 } else {
504 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
505 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000506 // If we are capturing a pointer by copy we don't need to do anything, just
507 // use the value that we get from the arguments.
508 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000509 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000510 if (!FO.RegisterCastedArgsOnly)
511 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000512 ++Cnt;
513 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000514 continue;
515 }
516
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000517 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
518 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000521 ArgLVal = CGF.MakeAddrLValue(
522 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
523 Args[Cnt]->getName(), ArgLVal),
524 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000525 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000526 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
527 const VariableArrayType *VAT = FD->getCapturedVLAType();
528 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000529 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000530 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000531 QualType VarTy = Var->getType();
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800532 Address ArgAddr = ArgLVal.getAddress(CGF);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000533 if (ArgLVal.getType()->isLValueReferenceType()) {
534 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
535 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
536 assert(ArgLVal.getType()->isPointerType());
537 ArgAddr = CGF.EmitLoadOfPointer(
538 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000539 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000540 if (!FO.RegisterCastedArgsOnly) {
541 LocalAddrs.insert(
542 {Args[Cnt],
543 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
544 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000545 } else if (I->capturesVariableByCopy()) {
546 assert(!FD->getType()->isAnyPointerType() &&
547 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000548 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000549 LocalAddrs.insert({Args[Cnt],
550 {Var, FO.UIntPtrCastRequired
551 ? castValueFromUintptr(
552 CGF, I->getLocation(), FD->getType(),
553 Args[Cnt]->getName(), ArgLVal)
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800554 : ArgLVal.getAddress(CGF)}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000555 } else {
556 // If 'this' is captured, load it into CXXThisValue.
557 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000558 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800559 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000560 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000561 ++Cnt;
562 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000563 }
564
Alexey Bataeve754b182017-08-09 19:38:53 +0000565 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000566}
567
568llvm::Function *
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500569CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
570 SourceLocation Loc) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000571 assert(
572 CapturedStmtInfo &&
573 "CapturedStmtInfo should be set when generating the captured function");
574 const CapturedDecl *CD = S.getCapturedDecl();
575 // Build the argument list.
576 bool NeedWrapperFunction =
Amy Huang53539bb2020-01-13 15:54:54 -0800577 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000578 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000579 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000580 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000581 SmallString<256> Buffer;
582 llvm::raw_svector_ostream Out(Buffer);
583 Out << CapturedStmtInfo->getHelperName();
584 if (NeedWrapperFunction)
585 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000586 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500587 Out.str(), Loc);
Alexey Bataeve754b182017-08-09 19:38:53 +0000588 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
589 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000590 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000591 for (const auto &LocalAddrPair : LocalAddrs) {
592 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000593 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
594 return LocalAddrPair.second.second;
595 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000596 }
597 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000598 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000599 for (const auto &VLASizePair : VLASizes)
600 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000601 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000602 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000603 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000604 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000605 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000607
Alexey Bataevefd884d2017-08-04 21:26:25 +0000608 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000609 /*RegisterCastedArgsOnly=*/true,
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500610 CapturedStmtInfo->getHelperName(), Loc);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000611 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000612 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000613 Args.clear();
614 LocalAddrs.clear();
615 VLASizes.clear();
616 llvm::Function *WrapperF =
617 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000618 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000619 llvm::SmallVector<llvm::Value *, 4> CallArgs;
620 for (const auto *Arg : Args) {
621 llvm::Value *CallArg;
622 auto I = LocalAddrs.find(Arg);
623 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000624 LValue LV = WrapperCGF.MakeAddrLValue(
625 I->second.second,
626 I->second.first ? I->second.first->getType() : Arg->getType(),
627 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000628 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000629 } else {
630 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000631 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000632 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000633 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000634 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000635 Arg->getType(),
636 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000637 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000638 }
639 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000640 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000641 }
Alexey Bataevc33ba8c2020-01-17 14:05:40 -0500642 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000643 WrapperCGF.FinishFunction();
644 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000645}
646
Alexey Bataev9959db52014-05-06 10:08:46 +0000647//===----------------------------------------------------------------------===//
648// OpenMP Directive Emission
649//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000650void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000651 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000652 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000653 // Perform element-by-element initialization.
654 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000655
656 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000657 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
658 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000659 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
660
Alexey Bataevddf3db92018-04-13 17:31:06 +0000661 llvm::Value *SrcBegin = SrcAddr.getPointer();
662 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000663 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000664 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000665 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000666 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
667 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
668 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000669 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
670 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000671
Alexey Bataev420d45b2015-04-14 05:11:24 +0000672 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000673 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000674 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000675
676 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
677
678 llvm::PHINode *SrcElementPHI =
679 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
680 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
681 Address SrcElementCurrent =
682 Address(SrcElementPHI,
683 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
684
685 llvm::PHINode *DestElementPHI =
686 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
687 DestElementPHI->addIncoming(DestBegin, EntryBB);
688 Address DestElementCurrent =
689 Address(DestElementPHI,
690 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000691
Alexey Bataev420d45b2015-04-14 05:11:24 +0000692 // Emit copy.
693 CopyGen(DestElementCurrent, SrcElementCurrent);
694
695 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000696 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000697 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000698 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000699 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000700 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000701 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
703 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000704 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
705 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000706
707 // Done.
708 EmitBlock(DoneBB, /*IsFinished=*/true);
709}
710
John McCall7f416cc2015-09-08 08:05:57 +0000711void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
712 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000713 const VarDecl *SrcVD, const Expr *Copy) {
714 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000715 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 if (BO && BO->getOpcode() == BO_Assign) {
717 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000718 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
719 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
720 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000721 } else {
722 // For arrays with complex element types perform element by element
723 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000724 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000725 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000726 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000727 // Working with the single array element, so have to remap
728 // destination and source variables to corresponding array
729 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000730 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000731 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
732 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000733 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000734 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000735 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000736 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000737 } else {
738 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000739 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000740 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
741 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000742 (void)Remap.Privatize();
743 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000744 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000745 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000746}
747
Alexey Bataev69c62a92015-04-15 04:52:20 +0000748bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
749 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000750 if (!HaveInsertPoint())
751 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000752 bool DeviceConstTarget =
753 getLangOpts().OpenMPIsDevice &&
754 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000755 bool FirstprivateIsLastprivate = false;
Alexey Bataev46978742020-01-30 10:46:11 -0500756 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000757 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
758 for (const auto *D : C->varlists())
Alexey Bataev46978742020-01-30 10:46:11 -0500759 Lastprivates.try_emplace(
760 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
761 C->getKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000762 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000763 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000764 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
765 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
766 // Force emission of the firstprivate copy if the directive does not emit
767 // outlined function, like omp for, omp simd, omp distribute etc.
768 bool MustEmitFirstprivateCopy =
769 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000770 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev46978742020-01-30 10:46:11 -0500771 const auto *IRef = C->varlist_begin();
772 const auto *InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000773 for (const Expr *IInit : C->private_copies()) {
774 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000775 bool ThisFirstprivateIsLastprivate =
776 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000777 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000778 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000779 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000780 !FD->getType()->isReferenceType() &&
781 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000782 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
783 ++IRef;
784 ++InitsRef;
785 continue;
786 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000787 // Do not emit copy for firstprivate constant variables in target regions,
788 // captured by reference.
789 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000790 FD && FD->getType()->isReferenceType() &&
791 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000792 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
793 OrigVD);
794 ++IRef;
795 ++InitsRef;
796 continue;
797 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000798 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000800 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000801 const auto *VDInit =
802 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000803 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000804 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000805 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
806 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataeve0ef04f2019-05-23 22:30:43 +0000807 LValue OriginalLVal;
808 if (!FD) {
809 // Check if the firstprivate variable is just a constant value.
810 ConstantEmission CE = tryEmitAsConstant(&DRE);
811 if (CE && !CE.isReference()) {
812 // Constant value, no need to create a copy.
813 ++IRef;
814 ++InitsRef;
815 continue;
816 }
817 if (CE && CE.isReference()) {
818 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
819 } else {
820 assert(!CE && "Expected non-constant firstprivate.");
821 OriginalLVal = EmitLValue(&DRE);
822 }
823 } else {
824 OriginalLVal = EmitLValue(&DRE);
825 }
Alexey Bataevfeddd642016-04-22 09:05:03 +0000826 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000827 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000828 // Emit VarDecl with copy init for arrays.
829 // Get the address of the original variable captured in current
830 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000831 IsRegistered = PrivateScope.addPrivate(
832 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
833 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
834 const Expr *Init = VD->getInit();
835 if (!isa<CXXConstructExpr>(Init) ||
836 isTrivialInitializer(Init)) {
837 // Perform simple memcpy.
838 LValue Dest =
839 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
840 EmitAggregateAssign(Dest, OriginalLVal, Type);
841 } else {
842 EmitOMPAggregateAssign(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800843 Emission.getAllocatedAddress(),
844 OriginalLVal.getAddress(*this), Type,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000845 [this, VDInit, Init](Address DestElement,
846 Address SrcElement) {
847 // Clean up any temporaries needed by the
848 // initialization.
849 RunCleanupsScope InitScope(*this);
850 // Emit initialization for single element.
851 setAddrOfLocalVar(VDInit, SrcElement);
852 EmitAnyExprToMem(Init, DestElement,
853 Init->getType().getQualifiers(),
854 /*IsInitializer*/ false);
855 LocalDeclMap.erase(VDInit);
856 });
857 }
858 EmitAutoVarCleanups(Emission);
859 return Emission.getAllocatedAddress();
860 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000861 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800862 Address OriginalAddr = OriginalLVal.getAddress(*this);
Alexey Bataev46978742020-01-30 10:46:11 -0500863 IsRegistered =
864 PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD,
865 ThisFirstprivateIsLastprivate,
866 OrigVD, &Lastprivates, IRef]() {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000867 // Emit private VarDecl with copy init.
868 // Remap temp VDInit variable to the address of the original
869 // variable (for proper handling of captured global variables).
870 setAddrOfLocalVar(VDInit, OriginalAddr);
871 EmitDecl(*VD);
872 LocalDeclMap.erase(VDInit);
Alexey Bataev46978742020-01-30 10:46:11 -0500873 if (ThisFirstprivateIsLastprivate &&
874 Lastprivates[OrigVD->getCanonicalDecl()] ==
875 OMPC_LASTPRIVATE_conditional) {
876 // Create/init special variable for lastprivate conditionals.
877 Address VDAddr =
878 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
879 *this, OrigVD);
880 llvm::Value *V = EmitLoadOfScalar(
881 MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(),
882 AlignmentSource::Decl),
883 (*IRef)->getExprLoc());
884 EmitStoreOfScalar(V,
885 MakeAddrLValue(VDAddr, (*IRef)->getType(),
886 AlignmentSource::Decl));
887 LocalDeclMap.erase(VD);
888 setAddrOfLocalVar(VD, VDAddr);
889 return VDAddr;
890 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000891 return GetAddrOfLocalVar(VD);
892 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000893 }
894 assert(IsRegistered &&
895 "firstprivate var already registered as private");
896 // Silence the warning about unused variable.
897 (void)IsRegistered;
898 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000899 ++IRef;
900 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000901 }
902 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000903 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000904}
905
Alexey Bataev03b340a2014-10-21 03:16:40 +0000906void CodeGenFunction::EmitOMPPrivateClause(
907 const OMPExecutableDirective &D,
908 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000909 if (!HaveInsertPoint())
910 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000911 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000912 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000913 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000914 for (const Expr *IInit : C->private_copies()) {
915 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000916 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000917 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
918 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
919 // Emit private VarDecl with copy init.
920 EmitDecl(*VD);
921 return GetAddrOfLocalVar(VD);
922 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000923 assert(IsRegistered && "private var already registered as private");
924 // Silence the warning about unused variable.
925 (void)IsRegistered;
926 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000927 ++IRef;
928 }
929 }
930}
931
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000932bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000933 if (!HaveInsertPoint())
934 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000935 // threadprivate_var1 = master_threadprivate_var1;
936 // operator=(threadprivate_var2, master_threadprivate_var2);
937 // ...
938 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000939 llvm::DenseSet<const VarDecl *> CopiedVars;
940 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000941 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000942 auto IRef = C->varlist_begin();
943 auto ISrcRef = C->source_exprs().begin();
944 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000945 for (const Expr *AssignOp : C->assignment_ops()) {
946 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000947 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000948 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000949 // Get the address of the master variable. If we are emitting code with
950 // TLS support, the address is passed from the master as field in the
951 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000952 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000953 if (getLangOpts().OpenMPUseTLS &&
954 getContext().getTargetInfo().isTLSSupported()) {
955 assert(CapturedStmtInfo->lookup(VD) &&
956 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000957 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
958 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800959 MasterAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000960 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000961 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000962 MasterAddr =
963 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
964 : CGM.GetAddrOfGlobal(VD),
965 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000966 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000967 // Get the address of the threadprivate variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800968 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000969 if (CopiedVars.size() == 1) {
970 // At first check if current thread is a master thread. If it is, no
971 // need to copy data.
972 CopyBegin = createBasicBlock("copyin.not.master");
973 CopyEnd = createBasicBlock("copyin.not.master.end");
974 Builder.CreateCondBr(
975 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000976 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000977 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
978 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000979 CopyBegin, CopyEnd);
980 EmitBlock(CopyBegin);
981 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000982 const auto *SrcVD =
983 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
984 const auto *DestVD =
985 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000986 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000987 }
988 ++IRef;
989 ++ISrcRef;
990 ++IDestRef;
991 }
992 }
993 if (CopyEnd) {
994 // Exit out of copying procedure for non-master thread.
995 EmitBlock(CopyEnd, /*IsFinished=*/true);
996 return true;
997 }
998 return false;
999}
1000
Alexey Bataev38e89532015-04-16 04:54:05 +00001001bool CodeGenFunction::EmitOMPLastprivateClauseInit(
1002 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001003 if (!HaveInsertPoint())
1004 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +00001005 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001006 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1007 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001008 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1009 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001010 SIMDLCVs.insert(
1011 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1012 }
1013 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001014 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001015 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +00001016 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001017 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
1018 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +00001019 break;
Alexey Bataev46978742020-01-30 10:46:11 -05001020 const auto *IRef = C->varlist_begin();
1021 const auto *IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001022 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001023 // Keep the address of the original variable for future update at the end
1024 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001025 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00001026 // Taskloops do not require additional initialization, it is done in
1027 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +00001028 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001029 const auto *DestVD =
1030 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1031 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001032 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1033 /*RefersToEnclosingVariableOrCapture=*/
1034 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1035 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001036 return EmitLValue(&DRE).getAddress(*this);
Alexey Bataev38e89532015-04-16 04:54:05 +00001037 });
1038 // Check if the variable is also a firstprivate: in this case IInit is
1039 // not generated. Initialization of this variable will happen in codegen
1040 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001041 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001042 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev46978742020-01-30 10:46:11 -05001043 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C,
1044 OrigVD]() {
1045 if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1046 Address VDAddr =
1047 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this,
1048 OrigVD);
1049 setAddrOfLocalVar(VD, VDAddr);
1050 return VDAddr;
1051 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00001052 // Emit private VarDecl with copy init.
1053 EmitDecl(*VD);
1054 return GetAddrOfLocalVar(VD);
1055 });
Alexey Bataevd130fd12015-05-13 10:23:02 +00001056 assert(IsRegistered &&
1057 "lastprivate var already registered as private");
1058 (void)IsRegistered;
1059 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001060 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001061 ++IRef;
1062 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001063 }
1064 }
1065 return HasAtLeastOneLastprivate;
1066}
1067
1068void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001069 const OMPExecutableDirective &D, bool NoFinals,
1070 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001071 if (!HaveInsertPoint())
1072 return;
Alexey Bataev38e89532015-04-16 04:54:05 +00001073 // Emit following code:
1074 // if (<IsLastIterCond>) {
1075 // orig_var1 = private_orig_var1;
1076 // ...
1077 // orig_varn = private_orig_varn;
1078 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001079 llvm::BasicBlock *ThenBB = nullptr;
1080 llvm::BasicBlock *DoneBB = nullptr;
1081 if (IsLastIterCond) {
Alexey Bataeva58da1a2019-12-27 09:44:43 -05001082 // Emit implicit barrier if at least one lastprivate conditional is found
1083 // and this is not a simd mode.
1084 if (!getLangOpts().OpenMPSimd &&
1085 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1086 [](const OMPLastprivateClause *C) {
1087 return C->getKind() == OMPC_LASTPRIVATE_conditional;
1088 })) {
1089 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1090 OMPD_unknown,
1091 /*EmitChecks=*/false,
1092 /*ForceSimpleCall=*/true);
1093 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001094 ThenBB = createBasicBlock(".omp.lastprivate.then");
1095 DoneBB = createBasicBlock(".omp.lastprivate.done");
1096 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1097 EmitBlock(ThenBB);
1098 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001099 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1100 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001101 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001102 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001103 for (const Expr *F : LoopDirective->finals()) {
1104 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001105 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1106 if (NoFinals)
1107 AlreadyEmittedVars.insert(D);
1108 else
1109 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001110 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001111 }
1112 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001113 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1114 auto IRef = C->varlist_begin();
1115 auto ISrcRef = C->source_exprs().begin();
1116 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001117 for (const Expr *AssignOp : C->assignment_ops()) {
1118 const auto *PrivateVD =
1119 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001120 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001121 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001122 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1123 // If lastprivate variable is a loop control variable for loop-based
1124 // directive, update its value before copyin back to original
1125 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001126 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001127 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001128 const auto *SrcVD =
1129 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1130 const auto *DestVD =
1131 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001132 // Get the address of the private variable.
1133 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001134 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001135 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001136 Address(Builder.CreateLoad(PrivateAddr),
1137 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataeva58da1a2019-12-27 09:44:43 -05001138 // Store the last value to the private copy in the last iteration.
1139 if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1140 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1141 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1142 (*IRef)->getExprLoc());
1143 // Get the address of the original variable.
1144 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001145 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001146 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001147 ++IRef;
1148 ++ISrcRef;
1149 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001150 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001151 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001152 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001153 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001154 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001155 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001156}
1157
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158void CodeGenFunction::EmitOMPReductionClauseInit(
1159 const OMPExecutableDirective &D,
1160 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001161 if (!HaveInsertPoint())
1162 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001163 SmallVector<const Expr *, 4> Shareds;
1164 SmallVector<const Expr *, 4> Privates;
1165 SmallVector<const Expr *, 4> ReductionOps;
1166 SmallVector<const Expr *, 4> LHSs;
1167 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001168 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001169 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001170 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001171 auto ILHS = C->lhs_exprs().begin();
1172 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001173 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001174 Shareds.emplace_back(Ref);
1175 Privates.emplace_back(*IPriv);
1176 ReductionOps.emplace_back(*IRed);
1177 LHSs.emplace_back(*ILHS);
1178 RHSs.emplace_back(*IRHS);
1179 std::advance(IPriv, 1);
1180 std::advance(IRed, 1);
1181 std::advance(ILHS, 1);
1182 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001183 }
1184 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001185 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1186 unsigned Count = 0;
1187 auto ILHS = LHSs.begin();
1188 auto IRHS = RHSs.begin();
1189 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001190 for (const Expr *IRef : Shareds) {
1191 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001192 // Emit private VarDecl with reduction init.
1193 RedCG.emitSharedLValue(*this, Count);
1194 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001195 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001196 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1197 RedCG.getSharedLValue(Count),
1198 [&Emission](CodeGenFunction &CGF) {
1199 CGF.EmitAutoVarInit(Emission);
1200 return true;
1201 });
1202 EmitAutoVarCleanups(Emission);
1203 Address BaseAddr = RedCG.adjustPrivateAddress(
1204 *this, Count, Emission.getAllocatedAddress());
1205 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001206 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001207 assert(IsRegistered && "private var already registered as private");
1208 // Silence the warning about unused variable.
1209 (void)IsRegistered;
1210
Alexey Bataevddf3db92018-04-13 17:31:06 +00001211 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1212 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001213 QualType Type = PrivateVD->getType();
1214 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1215 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001216 // Store the address of the original variable associated with the LHS
1217 // implicit variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001218 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1219 return RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001220 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001221 PrivateScope.addPrivate(
1222 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001223 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1224 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001225 // Store the address of the original variable associated with the LHS
1226 // implicit variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001227 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1228 return RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001229 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001230 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001231 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1232 ConvertTypeForMem(RHSVD->getType()),
1233 "rhs.begin");
1234 });
1235 } else {
1236 QualType Type = PrivateVD->getType();
1237 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001238 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001239 // Store the address of the original variable associated with the LHS
1240 // implicit variable.
1241 if (IsArray) {
1242 OriginalAddr = Builder.CreateElementBitCast(
1243 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1244 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001245 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001246 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001247 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001248 return IsArray
1249 ? Builder.CreateElementBitCast(
1250 GetAddrOfLocalVar(PrivateVD),
1251 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1252 : GetAddrOfLocalVar(PrivateVD);
1253 });
1254 }
1255 ++ILHS;
1256 ++IRHS;
1257 ++IPriv;
1258 ++Count;
1259 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001260}
1261
1262void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001263 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001264 if (!HaveInsertPoint())
1265 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001266 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001267 llvm::SmallVector<const Expr *, 8> LHSExprs;
1268 llvm::SmallVector<const Expr *, 8> RHSExprs;
1269 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001270 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001271 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001272 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001273 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001274 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1275 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1276 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1277 }
1278 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001279 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1280 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001281 ReductionKind == OMPD_simd;
1282 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001283 // Emit nowait reduction if nowait clause is present or directive is a
1284 // parallel directive (it always has implicit barrier).
1285 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001286 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001287 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001288 }
1289}
1290
Alexey Bataev61205072016-03-02 04:57:40 +00001291static void emitPostUpdateForReductionClause(
1292 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001293 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001294 if (!CGF.HaveInsertPoint())
1295 return;
1296 llvm::BasicBlock *DoneBB = nullptr;
1297 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001298 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001299 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001300 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001301 // If the first post-update expression is found, emit conditional
1302 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001303 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001304 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1305 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1306 CGF.EmitBlock(ThenBB);
1307 }
1308 }
1309 CGF.EmitIgnoredExpr(PostUpdate);
1310 }
1311 }
1312 if (DoneBB)
1313 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1314}
1315
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001316namespace {
1317/// Codegen lambda for appending distribute lower and upper bounds to outlined
1318/// parallel function. This is necessary for combined constructs such as
1319/// 'distribute parallel for'
1320typedef llvm::function_ref<void(CodeGenFunction &,
1321 const OMPExecutableDirective &,
1322 llvm::SmallVectorImpl<llvm::Value *> &)>
1323 CodeGenBoundParametersTy;
1324} // anonymous namespace
1325
Alexey Bataev46978742020-01-30 10:46:11 -05001326static void
1327checkForLastprivateConditionalUpdate(CodeGenFunction &CGF,
1328 const OMPExecutableDirective &S) {
1329 if (CGF.getLangOpts().OpenMP < 50)
1330 return;
1331 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1332 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1333 for (const Expr *Ref : C->varlists()) {
1334 if (!Ref->getType()->isScalarType())
1335 continue;
1336 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1337 if (!DRE)
1338 continue;
1339 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1340 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1341 }
1342 }
1343 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1344 for (const Expr *Ref : C->varlists()) {
1345 if (!Ref->getType()->isScalarType())
1346 continue;
1347 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1348 if (!DRE)
1349 continue;
1350 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1351 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1352 }
1353 }
1354 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1355 for (const Expr *Ref : C->varlists()) {
1356 if (!Ref->getType()->isScalarType())
1357 continue;
1358 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1359 if (!DRE)
1360 continue;
1361 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1362 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1363 }
1364 }
1365 // Privates should ne analyzed since they are not captured at all.
1366 // Task reductions may be skipped - tasks are ignored.
1367 // Firstprivates do not return value but may be passed by reference - no need
1368 // to check for updated lastprivate conditional.
1369 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1370 for (const Expr *Ref : C->varlists()) {
1371 if (!Ref->getType()->isScalarType())
1372 continue;
1373 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1374 if (!DRE)
1375 continue;
1376 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1377 }
1378 }
1379 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional(
1380 CGF, S, PrivateDecls);
1381}
1382
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001383static void emitCommonOMPParallelDirective(
1384 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1385 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1386 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001387 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001388 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001389 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1390 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001391 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001392 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001393 llvm::Value *NumThreads =
1394 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1395 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001396 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001397 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001398 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001399 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001400 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001401 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001402 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001403 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001404 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001405 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1406 if (C->getNameModifier() == OMPD_unknown ||
1407 C->getNameModifier() == OMPD_parallel) {
1408 IfCond = C->getCondition();
1409 break;
1410 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001411 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001412
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001413 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001414 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001415 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1416 // lower and upper bounds with the pragma 'for' chunking mechanism.
1417 // The following lambda takes care of appending the lower and upper bound
1418 // parameters when necessary
1419 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001420 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001421 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001422 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001423}
1424
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001425static void emitEmptyBoundParameters(CodeGenFunction &,
1426 const OMPExecutableDirective &,
1427 llvm::SmallVectorImpl<llvm::Value *> &) {}
1428
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001429void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Johannes Doerfert10fedd92019-12-26 11:23:38 -06001430 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
1431 // Check if we have any if clause associated with the directive.
1432 llvm::Value *IfCond = nullptr;
1433 if (const auto *C = S.getSingleClause<OMPIfClause>())
1434 IfCond = EmitScalarExpr(C->getCondition(),
1435 /*IgnoreResultAssign=*/true);
1436
1437 llvm::Value *NumThreads = nullptr;
1438 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1439 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1440 /*IgnoreResultAssign=*/true);
1441
1442 ProcBindKind ProcBind = OMP_PROC_BIND_default;
1443 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1444 ProcBind = ProcBindClause->getProcBindKind();
1445
1446 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1447
1448 // The cleanup callback that finalizes all variabels at the given location,
1449 // thus calls destructors etc.
1450 auto FiniCB = [this](InsertPointTy IP) {
1451 CGBuilderTy::InsertPointGuard IPG(Builder);
1452 assert(IP.getBlock()->end() != IP.getPoint() &&
1453 "OpenMP IR Builder should cause terminated block!");
1454 llvm::BasicBlock *IPBB = IP.getBlock();
1455 llvm::BasicBlock *DestBB = IPBB->splitBasicBlock(IP.getPoint());
1456 IPBB->getTerminator()->eraseFromParent();
1457 Builder.SetInsertPoint(IPBB);
1458 CodeGenFunction::JumpDest Dest = getJumpDestInCurrentScope(DestBB);
1459 EmitBranchThroughCleanup(Dest);
1460 };
1461
1462 // Privatization callback that performs appropriate action for
1463 // shared/private/firstprivate/lastprivate/copyin/... variables.
1464 //
1465 // TODO: This defaults to shared right now.
1466 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1467 llvm::Value &Val, llvm::Value *&ReplVal) {
1468 // The next line is appropriate only for variables (Val) with the
1469 // data-sharing attribute "shared".
1470 ReplVal = &Val;
1471
1472 return CodeGenIP;
1473 };
1474
1475 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1476 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1477
1478 auto BodyGenCB = [ParallelRegionBodyStmt,
1479 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1480 llvm::BasicBlock &ContinuationBB) {
1481 auto OldAllocaIP = AllocaInsertPt;
1482 AllocaInsertPt = &*AllocaIP.getPoint();
1483
1484 auto OldReturnBlock = ReturnBlock;
1485 ReturnBlock = getJumpDestInCurrentScope(&ContinuationBB);
1486
1487 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1488 CodeGenIPBB->splitBasicBlock(CodeGenIP.getPoint());
1489 llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator();
1490 CodeGenIPBBTI->removeFromParent();
1491
1492 Builder.SetInsertPoint(CodeGenIPBB);
1493
1494 EmitStmt(ParallelRegionBodyStmt);
1495
1496 Builder.Insert(CodeGenIPBBTI);
1497
1498 AllocaInsertPt = OldAllocaIP;
1499 ReturnBlock = OldReturnBlock;
1500 };
1501
1502 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1503 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1504 Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB,
1505 FiniCB, IfCond, NumThreads,
1506 ProcBind, S.hasCancel()));
1507 return;
1508 }
1509
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001510 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001511 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001512 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001513 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001514 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001515 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1516 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001517 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001518 // propagation master's thread values of threadprivate variables to local
1519 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001520 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001521 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001522 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001523 }
1524 CGF.EmitOMPPrivateClause(S, PrivateScope);
1525 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1526 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001527 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001528 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001529 };
Alexey Bataev46978742020-01-30 10:46:11 -05001530 {
1531 auto LPCRegion =
1532 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
1533 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1534 emitEmptyBoundParameters);
1535 emitPostUpdateForReductionClause(*this, S,
1536 [](CodeGenFunction &) { return nullptr; });
1537 }
1538 // Check for outer lastprivate conditional update.
1539 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataev9959db52014-05-06 10:08:46 +00001540}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001541
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001542static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1543 int MaxLevel, int Level = 0) {
1544 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1545 const Stmt *SimplifiedS = S->IgnoreContainers();
1546 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1547 PrettyStackTraceLoc CrashInfo(
1548 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1549 "LLVM IR generation of compound statement ('{}')");
1550
1551 // Keep track of the current cleanup stack depth, including debug scopes.
1552 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1553 for (const Stmt *CurStmt : CS->body())
1554 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1555 return;
1556 }
1557 if (SimplifiedS == NextLoop) {
1558 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1559 S = For->getBody();
1560 } else {
1561 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1562 "Expected canonical for loop or range-based for loop.");
1563 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1564 CGF.EmitStmt(CXXFor->getLoopVarStmt());
1565 S = CXXFor->getBody();
1566 }
1567 if (Level + 1 < MaxLevel) {
1568 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1569 S, /*TryImperfectlyNestedLoops=*/true);
1570 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1571 return;
1572 }
1573 }
1574 CGF.EmitStmt(S);
1575}
1576
Alexey Bataev0f34da12015-07-02 04:17:07 +00001577void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1578 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001579 RunCleanupsScope BodyScope(*this);
1580 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001581 for (const Expr *UE : D.updates())
1582 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001583 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001584 // In distribute directives only loop counters may be marked as linear, no
1585 // need to generate the code for them.
1586 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1587 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001588 for (const Expr *UE : C->updates())
1589 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001590 }
Alexander Musman3276a272015-03-21 10:12:56 +00001591 }
1592
Alexander Musmana5f070a2014-10-01 06:03:56 +00001593 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001594 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001595 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexey Bataevf8be4762019-08-14 19:30:06 +00001596 for (const Expr *E : D.finals_conditions()) {
1597 if (!E)
1598 continue;
1599 // Check that loop counter in non-rectangular nest fits into the iteration
1600 // space.
1601 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1602 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1603 getProfileCount(D.getBody()));
1604 EmitBlock(NextBB);
1605 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00001606 // Emit loop variables for C++ range loops.
1607 const Stmt *Body =
1608 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001609 // Emit loop body.
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001610 emitBody(*this, Body,
1611 OMPLoopDirective::tryToFindNextInnerLoop(
1612 Body, /*TryImperfectlyNestedLoops=*/true),
1613 D.getCollapsedNumber());
1614
Alexander Musmana5f070a2014-10-01 06:03:56 +00001615 // The end (updates/cleanups).
1616 EmitBlock(Continue.getBlock());
1617 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001618}
1619
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001620void CodeGenFunction::EmitOMPInnerLoop(
1621 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1622 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001623 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1624 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001625 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001626
1627 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001628 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001629 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001630 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001631 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1632 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001633
1634 // If there are any cleanups between here and the loop-exit scope,
1635 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001636 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001637 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001638 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001639
Alexey Bataevddf3db92018-04-13 17:31:06 +00001640 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001641
Alexey Bataev2df54a02015-03-12 08:53:29 +00001642 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001643 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001644 if (ExitBlock != LoopExit.getBlock()) {
1645 EmitBlock(ExitBlock);
1646 EmitBranchThroughCleanup(LoopExit);
1647 }
1648
1649 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001650 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001651
1652 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001653 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001654 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1655
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001656 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001657
1658 // Emit "IV = IV + 1" and a back-edge to the condition block.
1659 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001660 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001661 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001662 BreakContinueStack.pop_back();
1663 EmitBranch(CondBlock);
1664 LoopStack.pop();
1665 // Emit the fall-through block.
1666 EmitBlock(LoopExit.getBlock());
1667}
1668
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001669bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001670 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001671 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001672 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001673 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001674 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001675 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001676 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001677 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1678 if (const auto *Ref =
1679 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001680 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001681 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001682 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001683 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1684 VD->getInit()->getType(), VK_LValue,
1685 VD->getInit()->getExprLoc());
1686 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1687 VD->getType()),
1688 /*capturedByInit=*/false);
1689 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001690 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001691 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001692 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001693 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001694 // Emit the linear steps for the linear clauses.
1695 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001696 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1697 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001698 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001699 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001700 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001701 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001702 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001703 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001704}
1705
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001706void CodeGenFunction::EmitOMPLinearClauseFinal(
1707 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001708 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001709 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001710 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001711 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001712 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001713 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001714 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001715 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001716 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001717 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001718 // If the first post-update expression is found, emit conditional
1719 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001720 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001721 DoneBB = createBasicBlock(".omp.linear.pu.done");
1722 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1723 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001724 }
1725 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001726 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001727 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001728 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001729 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001730 Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001731 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001732 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001733 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001734 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001735 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001736 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001737 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001738 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001739 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001740 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001741 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001742}
1743
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001744static void emitAlignedClause(CodeGenFunction &CGF,
1745 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001746 if (!CGF.HaveInsertPoint())
1747 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001748 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Erich Keanef7593952019-10-11 14:59:44 +00001749 llvm::APInt ClauseAlignment(64, 0);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001750 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1751 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001752 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
Erich Keanef7593952019-10-11 14:59:44 +00001753 ClauseAlignment = AlignmentCI->getValue();
Alexander Musman09184fe2014-09-30 05:29:28 +00001754 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001755 for (const Expr *E : Clause->varlists()) {
Erich Keanef7593952019-10-11 14:59:44 +00001756 llvm::APInt Alignment(ClauseAlignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001757 if (Alignment == 0) {
1758 // OpenMP [2.8.1, Description]
1759 // If no optional parameter is specified, implementation-defined default
1760 // alignments for SIMD instructions on the target platforms are assumed.
1761 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001762 CGF.getContext()
1763 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1764 E->getType()->getPointeeType()))
1765 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001766 }
Erich Keanef7593952019-10-11 14:59:44 +00001767 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001768 "alignment is not power of 2");
1769 if (Alignment != 0) {
1770 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001771 CGF.EmitAlignmentAssumption(
Erich Keanef7593952019-10-11 14:59:44 +00001772 PtrValue, E, /*No second loc needed*/ SourceLocation(),
1773 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001774 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001775 }
1776 }
1777}
1778
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001779void CodeGenFunction::EmitOMPPrivateLoopCounters(
1780 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1781 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001782 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001783 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001784 for (const Expr *E : S.counters()) {
1785 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1786 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001787 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001788 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001789 EmitAutoVarCleanups(VarEmission);
1790 LocalDeclMap.erase(PrivateVD);
1791 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1792 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001793 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001794 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1795 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001796 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001797 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001798 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1799 E->getType(), VK_LValue, E->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001800 return EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001801 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001802 } else {
1803 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1804 return VarEmission.getAllocatedAddress();
1805 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001806 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001807 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001808 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001809 // Privatize extra loop counters used in loops for ordered(n) clauses.
1810 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1811 if (!C->getNumForLoops())
1812 continue;
1813 for (unsigned I = S.getCollapsedNumber(),
1814 E = C->getLoopNumIterations().size();
1815 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001816 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001817 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001818 // Override only those variables that can be captured to avoid re-emission
1819 // of the variables declared within the loops.
1820 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001821 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1822 return CreateMemTemp(DRE->getType(), VD->getName());
1823 });
1824 }
1825 }
1826 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001827}
1828
Alexey Bataev62dbb972015-04-22 11:59:37 +00001829static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1830 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1831 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001832 if (!CGF.HaveInsertPoint())
1833 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001834 {
1835 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001836 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001837 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001838 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001839 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001840 CGF.EmitIgnoredExpr(I);
1841 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001842 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00001843 // Create temp loop control variables with their init values to support
1844 // non-rectangular loops.
1845 CodeGenFunction::OMPMapVars PreCondVars;
1846 for (const Expr * E: S.dependent_counters()) {
1847 if (!E)
1848 continue;
1849 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1850 "dependent counter must not be an iterator.");
1851 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1852 Address CounterAddr =
1853 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1854 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1855 }
1856 (void)PreCondVars.apply(CGF);
1857 for (const Expr *E : S.dependent_inits()) {
1858 if (!E)
1859 continue;
1860 CGF.EmitIgnoredExpr(E);
1861 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001862 // Check that loop is executed at least one time.
1863 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00001864 PreCondVars.restore(CGF);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001865}
1866
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001867void CodeGenFunction::EmitOMPLinearClause(
1868 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1869 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001870 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001871 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1872 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001873 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1874 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001875 SIMDLCVs.insert(
1876 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1877 }
1878 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001879 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001880 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001881 for (const Expr *E : C->varlists()) {
1882 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1883 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001884 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001885 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001886 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001887 // Emit private VarDecl with copy init.
1888 EmitVarDecl(*PrivateVD);
1889 return GetAddrOfLocalVar(PrivateVD);
1890 });
1891 assert(IsRegistered && "linear var already registered as private");
1892 // Silence the warning about unused variable.
1893 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001894 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001895 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001896 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001897 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001898 }
1899 }
1900}
1901
Alexey Bataev45bfad52015-08-21 12:19:04 +00001902static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001903 const OMPExecutableDirective &D,
1904 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001905 if (!CGF.HaveInsertPoint())
1906 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001907 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001908 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1909 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001910 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001911 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1912 // In presence of finite 'safelen', it may be unsafe to mark all
1913 // the memory instructions parallel, because loop-carried
1914 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001915 if (!IsMonotonic)
1916 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001917 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001918 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1919 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001920 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001921 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001922 // In presence of finite 'safelen', it may be unsafe to mark all
1923 // the memory instructions parallel, because loop-carried
1924 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001925 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001926 }
1927}
1928
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001929void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1930 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001931 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001932 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001933 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001934 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataeva7815212020-02-03 12:08:16 -05001935 if (const auto *C = D.getSingleClause<OMPOrderClause>())
1936 if (C->getKind() == OMPC_ORDER_concurrent)
1937 LoopStack.setParallel(/*Enable=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001938}
1939
Alexey Bataevef549a82016-03-09 09:49:09 +00001940void CodeGenFunction::EmitOMPSimdFinal(
1941 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001942 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001943 if (!HaveInsertPoint())
1944 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001945 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001946 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001947 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001948 for (const Expr *F : D.finals()) {
1949 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1950 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1951 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001952 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1953 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001954 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001955 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001956 // If the first post-update expression is found, emit conditional
1957 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001958 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001959 DoneBB = createBasicBlock(".omp.final.done");
1960 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1961 EmitBlock(ThenBB);
1962 }
1963 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001964 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001965 if (CED) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001966 OrigAddr =
1967 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001968 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001969 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001970 /*RefersToEnclosingVariableOrCapture=*/false,
1971 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001972 OrigAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001973 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001974 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001975 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001976 (void)VarScope.Privatize();
1977 EmitIgnoredExpr(F);
1978 }
1979 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001980 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001981 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001982 if (DoneBB)
1983 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001984}
1985
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001986static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1987 const OMPLoopDirective &S,
1988 CodeGenFunction::JumpDest LoopExit) {
1989 CGF.EmitOMPLoopBody(S, LoopExit);
1990 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001991}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001992
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001993/// Emit a helper variable and return corresponding lvalue.
1994static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1995 const DeclRefExpr *Helper) {
1996 auto VDecl = cast<VarDecl>(Helper->getDecl());
1997 CGF.EmitVarDecl(*VDecl);
1998 return CGF.EmitLValue(Helper);
1999}
2000
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002001static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
2002 const RegionCodeGenTy &SimdInitGen,
2003 const RegionCodeGenTy &BodyCodeGen) {
Alexey Bataev0860db92019-12-19 10:01:10 -05002004 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
2005 PrePostActionTy &) {
2006 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002007 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2008 SimdInitGen(CGF);
2009
2010 BodyCodeGen(CGF);
2011 };
2012 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
2013 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2014 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
2015
2016 BodyCodeGen(CGF);
2017 };
2018 const Expr *IfCond = nullptr;
2019 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2020 if (CGF.getLangOpts().OpenMP >= 50 &&
2021 (C->getNameModifier() == OMPD_unknown ||
2022 C->getNameModifier() == OMPD_simd)) {
2023 IfCond = C->getCondition();
2024 break;
2025 }
2026 }
2027 if (IfCond) {
2028 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2029 } else {
2030 RegionCodeGenTy ThenRCG(ThenGen);
2031 ThenRCG(CGF);
2032 }
2033}
2034
Alexey Bataevf8365372017-11-17 17:57:25 +00002035static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
2036 PrePostActionTy &Action) {
2037 Action.Enter(CGF);
2038 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
2039 "Expected simd directive");
2040 OMPLoopScope PreInitScope(CGF, S);
2041 // if (PreCond) {
2042 // for (IV in 0..LastIteration) BODY;
2043 // <Final counter/linear vars updates>;
2044 // }
2045 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002046 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
2047 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
2048 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
2049 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2050 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2051 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002052
Alexey Bataevf8365372017-11-17 17:57:25 +00002053 // Emit: if (PreCond) - begin.
2054 // If the condition constant folds and can be elided, avoid emitting the
2055 // whole loop.
2056 bool CondConstant;
2057 llvm::BasicBlock *ContBlock = nullptr;
2058 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2059 if (!CondConstant)
2060 return;
2061 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002062 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00002063 ContBlock = CGF.createBasicBlock("simd.if.end");
2064 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
2065 CGF.getProfileCount(&S));
2066 CGF.EmitBlock(ThenBlock);
2067 CGF.incrementProfileCounter(&S);
2068 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002069
Alexey Bataevf8365372017-11-17 17:57:25 +00002070 // Emit the loop iteration variable.
2071 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002072 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00002073 CGF.EmitVarDecl(*IVDecl);
2074 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002075
Alexey Bataevf8365372017-11-17 17:57:25 +00002076 // Emit the iterations count variable.
2077 // If it is not a variable, Sema decided to calculate iterations count on
2078 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002079 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002080 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2081 // Emit calculation of the iterations count.
2082 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
2083 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002084
Alexey Bataevf8365372017-11-17 17:57:25 +00002085 emitAlignedClause(CGF, S);
2086 (void)CGF.EmitOMPLinearClauseInit(S);
2087 {
2088 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2089 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
2090 CGF.EmitOMPLinearClause(S, LoopScope);
2091 CGF.EmitOMPPrivateClause(S, LoopScope);
2092 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05002093 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2094 CGF, S, CGF.EmitLValue(S.getIterationVariable()));
Alexey Bataevf8365372017-11-17 17:57:25 +00002095 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2096 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002097 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2098 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevd08c0562019-11-19 12:07:54 -05002099
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002100 emitCommonSimdLoop(
2101 CGF, S,
2102 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2103 CGF.EmitOMPSimdInit(S);
2104 },
2105 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2106 CGF.EmitOMPInnerLoop(
2107 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2108 [&S](CodeGenFunction &CGF) {
2109 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
2110 CGF.EmitStopPoint(&S);
2111 },
2112 [](CodeGenFunction &) {});
2113 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00002114 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002115 // Emit final copy of the lastprivate variables at the end of loops.
2116 if (HasLastprivateClause)
2117 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2118 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002119 emitPostUpdateForReductionClause(CGF, S,
2120 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002121 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002122 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002123 // Emit: if (PreCond) - end.
2124 if (ContBlock) {
2125 CGF.EmitBranch(ContBlock);
2126 CGF.EmitBlock(ContBlock, true);
2127 }
2128}
2129
2130void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
2131 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2132 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002133 };
Alexey Bataev46978742020-01-30 10:46:11 -05002134 {
2135 auto LPCRegion =
2136 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2137 OMPLexicalScope Scope(*this, S, OMPD_unknown);
2138 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2139 }
2140 // Check for outer lastprivate conditional update.
2141 checkForLastprivateConditionalUpdate(*this, S);
Alexander Musman515ad8c2014-05-22 08:54:05 +00002142}
2143
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002144void CodeGenFunction::EmitOMPOuterLoop(
2145 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2146 CodeGenFunction::OMPPrivateScope &LoopScope,
2147 const CodeGenFunction::OMPLoopArguments &LoopArgs,
2148 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2149 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002150 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00002151
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002152 const Expr *IVExpr = S.getIterationVariable();
2153 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2154 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2155
Alexey Bataevddf3db92018-04-13 17:31:06 +00002156 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002157
2158 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002159 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002160 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002161 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00002162 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2163 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002164
2165 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002166 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002167 // UB = min(UB, GlobalUB) or
2168 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2169 // 'distribute parallel for')
2170 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002171 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002172 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002173 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002174 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002175 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002176 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002177 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002178 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002179 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002180
2181 // If there are any cleanups between here and the loop-exit scope,
2182 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002183 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002184 if (LoopScope.requiresCleanups())
2185 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2186
Alexey Bataevddf3db92018-04-13 17:31:06 +00002187 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002188 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2189 if (ExitBlock != LoopExit.getBlock()) {
2190 EmitBlock(ExitBlock);
2191 EmitBranchThroughCleanup(LoopExit);
2192 }
2193 EmitBlock(LoopBody);
2194
Alexander Musman92bdaab2015-03-12 13:37:50 +00002195 // Emit "IV = LB" (in case of static schedule, we have already calculated new
2196 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002197 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002198 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002199
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002200 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002201 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002202 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2203
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002204 emitCommonSimdLoop(
2205 *this, S,
2206 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
2207 // Generate !llvm.loop.parallel metadata for loads and stores for loops
2208 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva7815212020-02-03 12:08:16 -05002209 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002210 CGF.LoopStack.setParallel(!IsMonotonic);
Alexey Bataeva7815212020-02-03 12:08:16 -05002211 if (const auto *C = S.getSingleClause<OMPOrderClause>())
2212 if (C->getKind() == OMPC_ORDER_concurrent)
2213 CGF.LoopStack.setParallel(/*Enable=*/true);
2214 } else {
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002215 CGF.EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataeva7815212020-02-03 12:08:16 -05002216 }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002217 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002218 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2219 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2220 SourceLocation Loc = S.getBeginLoc();
2221 // when 'distribute' is not combined with a 'for':
2222 // while (idx <= UB) { BODY; ++idx; }
2223 // when 'distribute' is combined with a 'for'
2224 // (e.g. 'distribute parallel for')
2225 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2226 CGF.EmitOMPInnerLoop(
2227 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2228 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2229 CodeGenLoop(CGF, S, LoopExit);
2230 },
2231 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2232 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2233 });
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002234 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002235
2236 EmitBlock(Continue.getBlock());
2237 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002238 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002239 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002240 EmitIgnoredExpr(LoopArgs.NextLB);
2241 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002242 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002243
2244 EmitBranch(CondBlock);
2245 LoopStack.pop();
2246 // Emit the fall-through block.
2247 EmitBlock(LoopExit.getBlock());
2248
2249 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002250 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2251 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002252 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002253 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002254 };
2255 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002256}
2257
2258void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002259 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002260 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002261 const OMPLoopArguments &LoopArgs,
2262 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002263 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002264
2265 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002266 const bool DynamicOrOrdered =
2267 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002268
2269 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002270 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002271 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002272 "static non-chunked schedule does not need outer loop");
2273
2274 // Emit outer loop.
2275 //
2276 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2277 // When schedule(dynamic,chunk_size) is specified, the iterations are
2278 // distributed to threads in the team in chunks as the threads request them.
2279 // Each thread executes a chunk of iterations, then requests another chunk,
2280 // until no chunks remain to be distributed. Each chunk contains chunk_size
2281 // iterations, except for the last chunk to be distributed, which may have
2282 // fewer iterations. When no chunk_size is specified, it defaults to 1.
2283 //
2284 // When schedule(guided,chunk_size) is specified, the iterations are assigned
2285 // to threads in the team in chunks as the executing threads request them.
2286 // Each thread executes a chunk of iterations, then requests another chunk,
2287 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2288 // each chunk is proportional to the number of unassigned iterations divided
2289 // by the number of threads in the team, decreasing to 1. For a chunk_size
2290 // with value k (greater than 1), the size of each chunk is determined in the
2291 // same way, with the restriction that the chunks do not contain fewer than k
2292 // iterations (except for the last chunk to be assigned, which may have fewer
2293 // than k iterations).
2294 //
2295 // When schedule(auto) is specified, the decision regarding scheduling is
2296 // delegated to the compiler and/or runtime system. The programmer gives the
2297 // implementation the freedom to choose any possible mapping of iterations to
2298 // threads in the team.
2299 //
2300 // When schedule(runtime) is specified, the decision regarding scheduling is
2301 // deferred until run time, and the schedule and chunk size are taken from the
2302 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2303 // implementation defined
2304 //
2305 // while(__kmpc_dispatch_next(&LB, &UB)) {
2306 // idx = LB;
2307 // while (idx <= UB) { BODY; ++idx;
2308 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2309 // } // inner loop
2310 // }
2311 //
2312 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2313 // When schedule(static, chunk_size) is specified, iterations are divided into
2314 // chunks of size chunk_size, and the chunks are assigned to the threads in
2315 // the team in a round-robin fashion in the order of the thread number.
2316 //
2317 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2318 // while (idx <= UB) { BODY; ++idx; } // inner loop
2319 // LB = LB + ST;
2320 // UB = UB + ST;
2321 // }
2322 //
2323
2324 const Expr *IVExpr = S.getIterationVariable();
2325 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2326 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2327
2328 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002329 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2330 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002331 llvm::Value *LBVal = DispatchBounds.first;
2332 llvm::Value *UBVal = DispatchBounds.second;
2333 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2334 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002335 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002336 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002337 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002338 CGOpenMPRuntime::StaticRTInput StaticInit(
2339 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2340 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002341 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002342 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002343 }
2344
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002345 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2346 const unsigned IVSize,
2347 const bool IVSigned) {
2348 if (Ordered) {
2349 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2350 IVSigned);
2351 }
2352 };
2353
2354 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2355 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2356 OuterLoopArgs.IncExpr = S.getInc();
2357 OuterLoopArgs.Init = S.getInit();
2358 OuterLoopArgs.Cond = S.getCond();
2359 OuterLoopArgs.NextLB = S.getNextLowerBound();
2360 OuterLoopArgs.NextUB = S.getNextUpperBound();
2361 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2362 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002363}
2364
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002365static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2366 const unsigned IVSize, const bool IVSigned) {}
2367
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002368void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002369 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2370 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2371 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002372
Alexey Bataevddf3db92018-04-13 17:31:06 +00002373 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002374
2375 // Emit outer loop.
2376 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2377 // dynamic
2378 //
2379
2380 const Expr *IVExpr = S.getIterationVariable();
2381 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2382 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2383
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002384 CGOpenMPRuntime::StaticRTInput StaticInit(
2385 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2386 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002387 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002388
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002389 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002390 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002391 Expr *IncExpr;
2392 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2393 IncExpr = S.getDistInc();
2394 else
2395 IncExpr = S.getInc();
2396
2397 // this routine is shared by 'omp distribute parallel for' and
2398 // 'omp distribute': select the right EUB expression depending on the
2399 // directive
2400 OMPLoopArguments OuterLoopArgs;
2401 OuterLoopArgs.LB = LoopArgs.LB;
2402 OuterLoopArgs.UB = LoopArgs.UB;
2403 OuterLoopArgs.ST = LoopArgs.ST;
2404 OuterLoopArgs.IL = LoopArgs.IL;
2405 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2406 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2407 ? S.getCombinedEnsureUpperBound()
2408 : S.getEnsureUpperBound();
2409 OuterLoopArgs.IncExpr = IncExpr;
2410 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2411 ? S.getCombinedInit()
2412 : S.getInit();
2413 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2414 ? S.getCombinedCond()
2415 : S.getCond();
2416 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2417 ? S.getCombinedNextLowerBound()
2418 : S.getNextLowerBound();
2419 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2420 ? S.getCombinedNextUpperBound()
2421 : S.getNextUpperBound();
2422
2423 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2424 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2425 emitEmptyOrdered);
2426}
2427
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002428static std::pair<LValue, LValue>
2429emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2430 const OMPExecutableDirective &S) {
2431 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2432 LValue LB =
2433 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2434 LValue UB =
2435 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2436
2437 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2438 // parallel for') we need to use the 'distribute'
2439 // chunk lower and upper bounds rather than the whole loop iteration
2440 // space. These are parameters to the outlined function for 'parallel'
2441 // and we copy the bounds of the previous schedule into the
2442 // the current ones.
2443 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2444 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002445 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2446 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002447 PrevLBVal = CGF.EmitScalarConversion(
2448 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002449 LS.getIterationVariable()->getType(),
2450 LS.getPrevLowerBoundVariable()->getExprLoc());
2451 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2452 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002453 PrevUBVal = CGF.EmitScalarConversion(
2454 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002455 LS.getIterationVariable()->getType(),
2456 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002457
2458 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2459 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2460
2461 return {LB, UB};
2462}
2463
2464/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2465/// we need to use the LB and UB expressions generated by the worksharing
2466/// code generation support, whereas in non combined situations we would
2467/// just emit 0 and the LastIteration expression
2468/// This function is necessary due to the difference of the LB and UB
2469/// types for the RT emission routines for 'for_static_init' and
2470/// 'for_dispatch_init'
2471static std::pair<llvm::Value *, llvm::Value *>
2472emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2473 const OMPExecutableDirective &S,
2474 Address LB, Address UB) {
2475 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2476 const Expr *IVExpr = LS.getIterationVariable();
2477 // when implementing a dynamic schedule for a 'for' combined with a
2478 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2479 // is not normalized as each team only executes its own assigned
2480 // distribute chunk
2481 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002482 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002483 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002484 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002485 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002486 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002487}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002488
2489static void emitDistributeParallelForDistributeInnerBoundParams(
2490 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2491 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2492 const auto &Dir = cast<OMPLoopDirective>(S);
2493 LValue LB =
2494 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002495 llvm::Value *LBCast =
2496 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
2497 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002498 CapturedVars.push_back(LBCast);
2499 LValue UB =
2500 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2501
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002502 llvm::Value *UBCast =
2503 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
2504 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002505 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002506}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002507
2508static void
2509emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2510 const OMPLoopDirective &S,
2511 CodeGenFunction::JumpDest LoopExit) {
2512 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002513 PrePostActionTy &Action) {
2514 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002515 bool HasCancel = false;
2516 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2517 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2518 HasCancel = D->hasCancel();
2519 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2520 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002521 else if (const auto *D =
2522 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2523 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002524 }
2525 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2526 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002527 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2528 emitDistributeParallelForInnerBounds,
2529 emitDistributeParallelForDispatchBounds);
2530 };
2531
2532 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002533 CGF, S,
2534 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2535 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002536 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002537}
2538
Carlo Bertolli9925f152016-06-27 14:55:37 +00002539void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2540 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002541 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2542 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2543 S.getDistInc());
2544 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002545 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002546 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002547}
2548
Kelvin Li4a39add2016-07-05 05:00:15 +00002549void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2550 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002551 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2552 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2553 S.getDistInc());
2554 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002555 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002556 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002557}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002558
2559void CodeGenFunction::EmitOMPDistributeSimdDirective(
2560 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002561 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2562 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2563 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002564 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002565 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002566}
2567
Alexey Bataevf8365372017-11-17 17:57:25 +00002568void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2569 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2570 // Emit SPMD target parallel for region as a standalone region.
2571 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2572 emitOMPSimdRegion(CGF, S, Action);
2573 };
2574 llvm::Function *Fn;
2575 llvm::Constant *Addr;
2576 // Emit target region as a standalone region.
2577 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2578 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2579 assert(Fn && Addr && "Target device function emission failed.");
2580}
2581
Kelvin Li986330c2016-07-20 22:57:10 +00002582void CodeGenFunction::EmitOMPTargetSimdDirective(
2583 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002584 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2585 emitOMPSimdRegion(CGF, S, Action);
2586 };
2587 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002588}
2589
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002590namespace {
2591 struct ScheduleKindModifiersTy {
2592 OpenMPScheduleClauseKind Kind;
2593 OpenMPScheduleClauseModifier M1;
2594 OpenMPScheduleClauseModifier M2;
2595 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2596 OpenMPScheduleClauseModifier M1,
2597 OpenMPScheduleClauseModifier M2)
2598 : Kind(Kind), M1(M1), M2(M2) {}
2599 };
2600} // namespace
2601
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002602bool CodeGenFunction::EmitOMPWorksharingLoop(
2603 const OMPLoopDirective &S, Expr *EUB,
2604 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2605 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002606 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002607 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2608 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002609 EmitVarDecl(*IVDecl);
2610
2611 // Emit the iterations count variable.
2612 // If it is not a variable, Sema decided to calculate iterations count on each
2613 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002614 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002615 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2616 // Emit calculation of the iterations count.
2617 EmitIgnoredExpr(S.getCalcLastIteration());
2618 }
2619
Alexey Bataevddf3db92018-04-13 17:31:06 +00002620 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002621
Alexey Bataev38e89532015-04-16 04:54:05 +00002622 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002623 // Check pre-condition.
2624 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002625 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002626 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002627 // If the condition constant folds and can be elided, avoid emitting the
2628 // whole loop.
2629 bool CondConstant;
2630 llvm::BasicBlock *ContBlock = nullptr;
2631 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2632 if (!CondConstant)
2633 return false;
2634 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002635 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002636 ContBlock = createBasicBlock("omp.precond.end");
2637 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002638 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002639 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002640 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002641 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002642
Alexey Bataevea33dee2018-02-15 23:39:43 +00002643 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002644 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002645 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002646 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002647 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002648 else
2649 Ordered = true;
2650 }
2651
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002652 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002653 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002654 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002655 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002656
2657 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2658 LValue LB = Bounds.first;
2659 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002660 LValue ST =
2661 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2662 LValue IL =
2663 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2664
Alexander Musmanc6388682014-12-15 07:07:06 +00002665 // Emit 'then' code.
2666 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002667 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002668 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002669 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002670 // initialization of firstprivate variables and post-update of
2671 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002672 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002673 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002674 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002675 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002676 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05002677 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2678 *this, S, EmitLValue(S.getIterationVariable()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002679 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002680 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002681 EmitOMPPrivateLoopCounters(S, LoopScope);
2682 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002683 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002684 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2685 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002686
2687 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002688 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002689 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002690 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002691 ScheduleKind.Schedule = C->getScheduleKind();
2692 ScheduleKind.M1 = C->getFirstScheduleModifier();
2693 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002694 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002695 } else {
2696 // Default behaviour for schedule clause.
2697 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002698 *this, S, ScheduleKind.Schedule, ChunkExpr);
2699 }
2700 bool HasChunkSizeOne = false;
2701 llvm::Value *Chunk = nullptr;
2702 if (ChunkExpr) {
2703 Chunk = EmitScalarExpr(ChunkExpr);
2704 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2705 S.getIterationVariable()->getType(),
2706 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002707 Expr::EvalResult Result;
2708 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2709 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002710 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002711 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002712 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002713 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2714 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002715 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2716 // If the static schedule kind is specified or if the ordered clause is
2717 // specified, and if no monotonic modifier is specified, the effect will
2718 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002719 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2720 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2721 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2722 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2723 /* Chunked */ Chunk != nullptr) ||
2724 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002725 !Ordered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002726 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002727 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002728 emitCommonSimdLoop(
2729 *this, S,
2730 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva7815212020-02-03 12:08:16 -05002731 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002732 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataeva7815212020-02-03 12:08:16 -05002733 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
2734 if (C->getKind() == OMPC_ORDER_concurrent)
2735 CGF.LoopStack.setParallel(/*Enable=*/true);
2736 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002737 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002738 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2739 &S, ScheduleKind, LoopExit,
2740 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2741 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2742 // When no chunk_size is specified, the iteration space is divided
2743 // into chunks that are approximately equal in size, and at most
2744 // one chunk is distributed to each thread. Note that the size of
2745 // the chunks is unspecified in this case.
2746 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002747 IVSize, IVSigned, Ordered, IL.getAddress(CGF),
2748 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002749 StaticChunkedOne ? Chunk : nullptr);
2750 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2751 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2752 StaticInit);
2753 // UB = min(UB, GlobalUB);
2754 if (!StaticChunkedOne)
2755 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2756 // IV = LB;
2757 CGF.EmitIgnoredExpr(S.getInit());
2758 // For unchunked static schedule generate:
2759 //
2760 // while (idx <= UB) {
2761 // BODY;
2762 // ++idx;
2763 // }
2764 //
2765 // For static schedule with chunk one:
2766 //
2767 // while (IV <= PrevUB) {
2768 // BODY;
2769 // IV += ST;
2770 // }
2771 CGF.EmitOMPInnerLoop(
2772 S, LoopScope.requiresCleanups(),
2773 StaticChunkedOne ? S.getCombinedParForInDistCond()
2774 : S.getCond(),
2775 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2776 [&S, LoopExit](CodeGenFunction &CGF) {
2777 CGF.EmitOMPLoopBody(S, LoopExit);
2778 CGF.EmitStopPoint(&S);
2779 },
2780 [](CodeGenFunction &) {});
2781 });
Alexey Bataev0f34da12015-07-02 04:17:07 +00002782 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002783 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002784 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002785 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002786 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002787 };
2788 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002789 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002790 const bool IsMonotonic =
2791 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2792 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2793 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2794 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002795 // Emit the outer loop, which requests its work chunk [LB..UB] from
2796 // runtime and runs the inner loop to process it.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002797 const OMPLoopArguments LoopArguments(
2798 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
2799 IL.getAddress(*this), Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002800 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002801 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002802 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002803 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002804 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2805 return CGF.Builder.CreateIsNotNull(
2806 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2807 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002808 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002809 EmitOMPReductionClauseFinal(
2810 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2811 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2812 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002813 // Emit post-update of the reduction variables if IsLastIter != 0.
2814 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002815 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002816 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002817 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002818 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002819 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2820 if (HasLastprivateClause)
2821 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002822 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002823 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002824 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002825 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002826 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002827 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002828 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002829 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002830 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002831 if (ContBlock) {
2832 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002833 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002834 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002835 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002836 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002837}
2838
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002839/// The following two functions generate expressions for the loop lower
2840/// and upper bounds in case of static and dynamic (dispatch) schedule
2841/// of the associated 'for' or 'distribute' loop.
2842static std::pair<LValue, LValue>
2843emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002844 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002845 LValue LB =
2846 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2847 LValue UB =
2848 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2849 return {LB, UB};
2850}
2851
2852/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2853/// consider the lower and upper bound expressions generated by the
2854/// worksharing loop support, but we use 0 and the iteration space size as
2855/// constants
2856static std::pair<llvm::Value *, llvm::Value *>
2857emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2858 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002859 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002860 const Expr *IVExpr = LS.getIterationVariable();
2861 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2862 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2863 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2864 return {LBVal, UBVal};
2865}
2866
Alexander Musmanc6388682014-12-15 07:07:06 +00002867void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002868 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002869 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2870 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002871 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002872 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2873 emitForLoopBounds,
2874 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002875 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002876 {
Alexey Bataev46978742020-01-30 10:46:11 -05002877 auto LPCRegion =
2878 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev475a7442018-01-12 19:39:11 +00002879 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002880 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2881 S.hasCancel());
2882 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002883
2884 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002885 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002886 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataev46978742020-01-30 10:46:11 -05002887 // Check for outer lastprivate conditional update.
2888 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002889}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002890
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002891void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002892 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002893 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2894 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002895 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2896 emitForLoopBounds,
2897 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002899 {
Alexey Bataev46978742020-01-30 10:46:11 -05002900 auto LPCRegion =
2901 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev475a7442018-01-12 19:39:11 +00002902 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002903 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2904 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002905
2906 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002907 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002908 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataev46978742020-01-30 10:46:11 -05002909 // Check for outer lastprivate conditional update.
2910 checkForLastprivateConditionalUpdate(*this, S);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002911}
2912
Alexey Bataev2df54a02015-03-12 08:53:29 +00002913static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2914 const Twine &Name,
2915 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002916 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002917 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002918 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002919 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002920}
2921
Alexey Bataev3392d762016-02-16 11:18:12 +00002922void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002923 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2924 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002925 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002926 auto &&CodeGen = [&S, CapturedStmt, CS,
2927 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2928 ASTContext &C = CGF.getContext();
2929 QualType KmpInt32Ty =
2930 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002931 // Emit helper vars inits.
2932 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2933 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002934 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2935 ? CGF.Builder.getInt32(CS->size() - 1)
2936 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002937 LValue UB =
2938 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2939 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2940 CGF.Builder.getInt32(1));
2941 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2942 CGF.Builder.getInt32(0));
2943 // Loop counter.
2944 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002945 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002946 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002947 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002948 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2949 // Generate condition for loop.
2950 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002951 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002952 // Increment for loop counter.
2953 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002954 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002955 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002956 // Iterate through all sections and emit a switch construct:
2957 // switch (IV) {
2958 // case 0:
2959 // <SectionStmt[0]>;
2960 // break;
2961 // ...
2962 // case <NumSection> - 1:
2963 // <SectionStmt[<NumSection> - 1]>;
2964 // break;
2965 // }
2966 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002967 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2968 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002969 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002970 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002971 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002972 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002973 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002974 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2975 CGF.EmitBlock(CaseBB);
2976 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002977 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002978 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002979 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002980 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002981 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002982 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002983 CGF.EmitBlock(CaseBB);
2984 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002985 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002986 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002987 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002988 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002989 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002990
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002991 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2992 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002993 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002994 // initialization of firstprivate variables and post-update of lastprivate
2995 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002996 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002997 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002998 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002999 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003000 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05003001 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003002 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
3003 CGF.EmitOMPReductionClauseInit(S, LoopScope);
3004 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003005 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3006 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00003007
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003008 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003009 OpenMPScheduleTy ScheduleKind;
3010 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003011 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003012 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
3013 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003014 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003015 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003016 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003017 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00003018 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003019 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
3020 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
3021 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003022 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003023 // while (idx <= UB) { BODY; ++idx; }
3024 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
3025 [](CodeGenFunction &) {});
3026 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00003027 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003028 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00003029 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00003030 };
3031 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003032 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00003033 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003034 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
3035 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003036 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00003037 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003038
3039 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3040 if (HasLastprivates)
3041 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003042 S, /*NoFinals=*/false,
3043 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003044 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00003045 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003046
3047 bool HasCancel = false;
3048 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
3049 HasCancel = OSD->hasCancel();
3050 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
3051 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00003052 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003053 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
3054 HasCancel);
3055 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
3056 // clause. Otherwise the barrier will be generated by the codegen for the
3057 // directive.
3058 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00003059 // Emit implicit barrier to synchronize threads and avoid data races on
3060 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003061 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003062 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00003063 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00003064}
Alexey Bataev2df54a02015-03-12 08:53:29 +00003065
Alexey Bataev68adb7d2015-04-14 03:29:22 +00003066void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00003067 {
Alexey Bataev46978742020-01-30 10:46:11 -05003068 auto LPCRegion =
3069 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev475a7442018-01-12 19:39:11 +00003070 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00003071 EmitSections(S);
3072 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00003073 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003074 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003075 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00003076 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00003077 }
Alexey Bataev46978742020-01-30 10:46:11 -05003078 // Check for outer lastprivate conditional update.
3079 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00003080}
3081
3082void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003083 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003084 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003085 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003086 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003087 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
3088 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003089}
3090
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003091void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003092 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00003093 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003094 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003095 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003096 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00003097 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 // Build a list of copyprivate variables along with helper expressions
3099 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003100 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003101 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00003102 DestExprs.append(C->destination_exprs().begin(),
3103 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003104 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003105 AssignmentOps.append(C->assignment_ops().begin(),
3106 C->assignment_ops().end());
3107 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003108 // Emit code for 'single' region along with 'copyprivate' clauses
3109 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3110 Action.Enter(CGF);
3111 OMPPrivateScope SingleScope(CGF);
3112 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
3113 CGF.EmitOMPPrivateClause(S, SingleScope);
3114 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00003115 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003116 };
Alexey Bataev3392d762016-02-16 11:18:12 +00003117 {
Alexey Bataev46978742020-01-30 10:46:11 -05003118 auto LPCRegion =
3119 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev475a7442018-01-12 19:39:11 +00003120 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003121 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00003122 CopyprivateVars, DestExprs,
3123 SrcExprs, AssignmentOps);
3124 }
3125 // Emit an implicit barrier at the end (to avoid data race on firstprivate
3126 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00003127 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00003128 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003129 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003130 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00003131 }
Alexey Bataev46978742020-01-30 10:46:11 -05003132 // Check for outer lastprivate conditional update.
3133 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003134}
3135
cchen47d60942019-12-05 13:43:48 -05003136static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003137 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3138 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003139 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003140 };
cchen47d60942019-12-05 13:43:48 -05003141 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3142}
3143
3144void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003145 OMPLexicalScope Scope(*this, S, OMPD_unknown);
cchen47d60942019-12-05 13:43:48 -05003146 emitMaster(*this, S);
Alexander Musman80c22892014-07-17 08:54:58 +00003147}
3148
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003149void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003150 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3151 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003152 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003153 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003154 const Expr *Hint = nullptr;
3155 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00003156 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00003157 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003158 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
3159 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003160 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003161}
3162
Alexey Bataev671605e2015-04-13 05:28:11 +00003163void CodeGenFunction::EmitOMPParallelForDirective(
3164 const OMPParallelForDirective &S) {
3165 // Emit directive as a combined directive that consists of two implicit
3166 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003167 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3168 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00003169 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003170 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3171 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00003172 };
Alexey Bataev46978742020-01-30 10:46:11 -05003173 {
3174 auto LPCRegion =
3175 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3176 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
3177 emitEmptyBoundParameters);
3178 }
3179 // Check for outer lastprivate conditional update.
3180 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003181}
3182
Alexander Musmane4e893b2014-09-23 09:33:00 +00003183void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003184 const OMPParallelForSimdDirective &S) {
3185 // Emit directive as a combined directive that consists of two implicit
3186 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003187 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3188 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003189 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3190 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003191 };
Alexey Bataev46978742020-01-30 10:46:11 -05003192 {
3193 auto LPCRegion =
3194 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3195 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
3196 emitEmptyBoundParameters);
3197 }
3198 // Check for outer lastprivate conditional update.
3199 checkForLastprivateConditionalUpdate(*this, S);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003200}
3201
cchen47d60942019-12-05 13:43:48 -05003202void CodeGenFunction::EmitOMPParallelMasterDirective(
3203 const OMPParallelMasterDirective &S) {
3204 // Emit directive as a combined directive that consists of two implicit
3205 // directives: 'parallel' with 'master' directive.
3206 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3207 Action.Enter(CGF);
3208 OMPPrivateScope PrivateScope(CGF);
3209 bool Copyins = CGF.EmitOMPCopyinClause(S);
3210 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3211 if (Copyins) {
3212 // Emit implicit barrier to synchronize threads and avoid data races on
3213 // propagation master's thread values of threadprivate variables to local
3214 // instances of that variables of all other implicit threads.
3215 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3216 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3217 /*ForceSimpleCall=*/true);
3218 }
3219 CGF.EmitOMPPrivateClause(S, PrivateScope);
3220 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3221 (void)PrivateScope.Privatize();
3222 emitMaster(CGF, S);
3223 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3224 };
Alexey Bataev46978742020-01-30 10:46:11 -05003225 {
3226 auto LPCRegion =
3227 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3228 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
3229 emitEmptyBoundParameters);
3230 emitPostUpdateForReductionClause(*this, S,
3231 [](CodeGenFunction &) { return nullptr; });
3232 }
3233 // Check for outer lastprivate conditional update.
3234 checkForLastprivateConditionalUpdate(*this, S);
cchen47d60942019-12-05 13:43:48 -05003235}
3236
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003237void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00003238 const OMPParallelSectionsDirective &S) {
3239 // Emit directive as a combined directive that consists of two implicit
3240 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003241 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3242 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003243 CGF.EmitSections(S);
3244 };
Alexey Bataev46978742020-01-30 10:46:11 -05003245 {
3246 auto LPCRegion =
3247 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3248 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
3249 emitEmptyBoundParameters);
3250 }
3251 // Check for outer lastprivate conditional update.
3252 checkForLastprivateConditionalUpdate(*this, S);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003253}
3254
Alexey Bataev475a7442018-01-12 19:39:11 +00003255void CodeGenFunction::EmitOMPTaskBasedDirective(
3256 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
3257 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
3258 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003259 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003260 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003261 auto I = CS->getCapturedDecl()->param_begin();
3262 auto PartId = std::next(I);
3263 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003264 // Check if the task is final
3265 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3266 // If the condition constant folds and can be elided, try to avoid emitting
3267 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003268 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003269 bool CondConstant;
3270 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3271 Data.Final.setInt(CondConstant);
3272 else
3273 Data.Final.setPointer(EvaluateExprAsBool(Cond));
3274 } else {
3275 // By default the task is not final.
3276 Data.Final.setInt(/*IntVal=*/false);
3277 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003278 // Check if the task has 'priority' clause.
3279 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003280 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00003281 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003282 Data.Priority.setPointer(EmitScalarConversion(
3283 EmitScalarExpr(Prio), Prio->getType(),
3284 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3285 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003286 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003287 // The first function argument for tasks is a thread id, the second one is a
3288 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003289 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
3290 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003291 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003292 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003293 for (const Expr *IInit : C->private_copies()) {
3294 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003295 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003296 Data.PrivateVars.push_back(*IRef);
3297 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003298 }
3299 ++IRef;
3300 }
3301 }
3302 EmittedAsPrivate.clear();
3303 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003304 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003305 auto IRef = C->varlist_begin();
3306 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003307 for (const Expr *IInit : C->private_copies()) {
3308 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003309 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003310 Data.FirstprivateVars.push_back(*IRef);
3311 Data.FirstprivateCopies.push_back(IInit);
3312 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003313 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003314 ++IRef;
3315 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003316 }
3317 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003318 // Get list of lastprivate variables (for taskloops).
3319 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3320 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3321 auto IRef = C->varlist_begin();
3322 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003323 for (const Expr *IInit : C->private_copies()) {
3324 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003325 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3326 Data.LastprivateVars.push_back(*IRef);
3327 Data.LastprivateCopies.push_back(IInit);
3328 }
3329 LastprivateDstsOrigs.insert(
3330 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3331 cast<DeclRefExpr>(*IRef)});
3332 ++IRef;
3333 ++ID;
3334 }
3335 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003336 SmallVector<const Expr *, 4> LHSs;
3337 SmallVector<const Expr *, 4> RHSs;
3338 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3339 auto IPriv = C->privates().begin();
3340 auto IRed = C->reduction_ops().begin();
3341 auto ILHS = C->lhs_exprs().begin();
3342 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003343 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003344 Data.ReductionVars.emplace_back(Ref);
3345 Data.ReductionCopies.emplace_back(*IPriv);
3346 Data.ReductionOps.emplace_back(*IRed);
3347 LHSs.emplace_back(*ILHS);
3348 RHSs.emplace_back(*IRHS);
3349 std::advance(IPriv, 1);
3350 std::advance(IRed, 1);
3351 std::advance(ILHS, 1);
3352 std::advance(IRHS, 1);
3353 }
3354 }
3355 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003356 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003357 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00003358 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003359 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003360 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00003361 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3362 CapturedRegion](CodeGenFunction &CGF,
3363 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003364 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00003365 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003366 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3367 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003368 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3369 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003370 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003371 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3372 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3373 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3374 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00003375 // Map privates.
3376 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3377 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3378 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003379 for (const Expr *E : Data.PrivateVars) {
3380 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003381 Address PrivatePtr = CGF.CreateMemTemp(
3382 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003383 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003384 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003385 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003386 for (const Expr *E : Data.FirstprivateVars) {
3387 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003388 Address PrivatePtr =
3389 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3390 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003391 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003392 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003393 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003394 for (const Expr *E : Data.LastprivateVars) {
3395 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003396 Address PrivatePtr =
3397 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3398 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003399 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003400 CallArgs.push_back(PrivatePtr.getPointer());
3401 }
James Y Knight9871db02019-02-05 16:42:33 +00003402 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3403 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003404 for (const auto &Pair : LastprivateDstsOrigs) {
3405 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003406 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3407 /*RefersToEnclosingVariableOrCapture=*/
3408 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3409 Pair.second->getType(), VK_LValue,
3410 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003411 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003412 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003413 });
3414 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003415 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003416 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3417 CGF.getContext().getDeclAlign(Pair.first));
3418 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3419 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003420 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003421 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003422 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003423 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3424 Data.ReductionOps);
3425 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3426 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3427 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3428 RedCG.emitSharedLValue(CGF, Cnt);
3429 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003430 // FIXME: This must removed once the runtime library is fixed.
3431 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003432 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003433 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003434 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003435 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003436 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003437 Replacement =
3438 Address(CGF.EmitScalarConversion(
3439 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3440 CGF.getContext().getPointerType(
3441 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003442 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003443 Replacement.getAlignment());
3444 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3445 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3446 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003447 }
3448 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003449 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003450 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003451 SmallVector<const Expr *, 4> InRedVars;
3452 SmallVector<const Expr *, 4> InRedPrivs;
3453 SmallVector<const Expr *, 4> InRedOps;
3454 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3455 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3456 auto IPriv = C->privates().begin();
3457 auto IRed = C->reduction_ops().begin();
3458 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003459 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003460 InRedVars.emplace_back(Ref);
3461 InRedPrivs.emplace_back(*IPriv);
3462 InRedOps.emplace_back(*IRed);
3463 TaskgroupDescriptors.emplace_back(*ITD);
3464 std::advance(IPriv, 1);
3465 std::advance(IRed, 1);
3466 std::advance(ITD, 1);
3467 }
3468 }
3469 // Privatize in_reduction items here, because taskgroup descriptors must be
3470 // privatized earlier.
3471 OMPPrivateScope InRedScope(CGF);
3472 if (!InRedVars.empty()) {
3473 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3474 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3475 RedCG.emitSharedLValue(CGF, Cnt);
3476 RedCG.emitAggregateType(CGF, Cnt);
3477 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003478 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003479 // FIXME: This must removed once the runtime library is fixed.
3480 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003481 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003482 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003483 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003484 llvm::Value *ReductionsPtr =
3485 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3486 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003487 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003488 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003489 Replacement = Address(
3490 CGF.EmitScalarConversion(
3491 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3492 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003493 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003494 Replacement.getAlignment());
3495 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3496 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3497 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003498 }
3499 }
3500 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003501
3502 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003503 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003504 };
James Y Knight9871db02019-02-05 16:42:33 +00003505 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003506 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3507 Data.NumberOfParts);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003508 OMPLexicalScope Scope(*this, S, llvm::None,
Alexey Bataev61205822019-12-04 09:50:21 -05003509 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3510 !isOpenMPSimdDirective(S.getDirectiveKind()));
Alexey Bataev7292c292016-04-25 12:22:29 +00003511 TaskGen(*this, OutlinedFn, Data);
3512}
3513
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003514static ImplicitParamDecl *
3515createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003516 QualType Ty, CapturedDecl *CD,
3517 SourceLocation Loc) {
3518 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3519 ImplicitParamDecl::Other);
3520 auto *OrigRef = DeclRefExpr::Create(
3521 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3522 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3523 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3524 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003525 auto *PrivateRef = DeclRefExpr::Create(
3526 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003527 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003528 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003529 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3530 ImplicitParamDecl::Other);
3531 auto *InitRef = DeclRefExpr::Create(
3532 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3533 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003534 PrivateVD->setInitStyle(VarDecl::CInit);
3535 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3536 InitRef, /*BasePath=*/nullptr,
3537 VK_RValue));
3538 Data.FirstprivateVars.emplace_back(OrigRef);
3539 Data.FirstprivateCopies.emplace_back(PrivateRef);
3540 Data.FirstprivateInits.emplace_back(InitRef);
3541 return OrigVD;
3542}
3543
3544void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3545 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3546 OMPTargetDataInfo &InputInfo) {
3547 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003548 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3549 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3550 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3551 auto I = CS->getCapturedDecl()->param_begin();
3552 auto PartId = std::next(I);
3553 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003554 OMPTaskDataTy Data;
3555 // The task is not final.
3556 Data.Final.setInt(/*IntVal=*/false);
3557 // Get list of firstprivate variables.
3558 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3559 auto IRef = C->varlist_begin();
3560 auto IElemInitRef = C->inits().begin();
3561 for (auto *IInit : C->private_copies()) {
3562 Data.FirstprivateVars.push_back(*IRef);
3563 Data.FirstprivateCopies.push_back(IInit);
3564 Data.FirstprivateInits.push_back(*IElemInitRef);
3565 ++IRef;
3566 ++IElemInitRef;
3567 }
3568 }
3569 OMPPrivateScope TargetScope(*this);
3570 VarDecl *BPVD = nullptr;
3571 VarDecl *PVD = nullptr;
3572 VarDecl *SVD = nullptr;
3573 if (InputInfo.NumberOfTargetItems > 0) {
3574 auto *CD = CapturedDecl::Create(
3575 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3576 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3577 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003578 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003579 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003580 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003581 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003582 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003583 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003584 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003585 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003586 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003587 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003588 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003589 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003590 TargetScope.addPrivate(
3591 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3592 TargetScope.addPrivate(PVD,
3593 [&InputInfo]() { return InputInfo.PointersArray; });
3594 TargetScope.addPrivate(SVD,
3595 [&InputInfo]() { return InputInfo.SizesArray; });
3596 }
3597 (void)TargetScope.Privatize();
3598 // Build list of dependences.
3599 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003600 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003601 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003602 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3603 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3604 // Set proper addresses for generated private copies.
3605 OMPPrivateScope Scope(CGF);
3606 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003607 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3608 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003609 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003610 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3611 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3612 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3613 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003614 // Map privates.
3615 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3616 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3617 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003618 for (const Expr *E : Data.FirstprivateVars) {
3619 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003620 Address PrivatePtr =
3621 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3622 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003623 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003624 CallArgs.push_back(PrivatePtr.getPointer());
3625 }
James Y Knight9871db02019-02-05 16:42:33 +00003626 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3627 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003628 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003629 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3630 CGF.getContext().getDeclAlign(Pair.first));
3631 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3632 }
3633 }
3634 // Privatize all private variables except for in_reduction items.
3635 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003636 if (InputInfo.NumberOfTargetItems > 0) {
3637 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003638 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003639 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003640 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003641 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003642 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003643 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003644
3645 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003646 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003647 BodyGen(CGF);
3648 };
James Y Knight9871db02019-02-05 16:42:33 +00003649 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003650 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3651 Data.NumberOfParts);
3652 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3653 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3654 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3655 SourceLocation());
3656
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003657 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003658 SharedsTy, CapturedStruct, &IfCond, Data);
3659}
3660
Alexey Bataev7292c292016-04-25 12:22:29 +00003661void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3662 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003663 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003664 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3665 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003666 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003667 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3668 if (C->getNameModifier() == OMPD_unknown ||
3669 C->getNameModifier() == OMPD_task) {
3670 IfCond = C->getCondition();
3671 break;
3672 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003673 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003674
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003675 OMPTaskDataTy Data;
3676 // Check if we should emit tied or untied task.
3677 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003678 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3679 CGF.EmitStmt(CS->getCapturedStmt());
3680 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003681 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003682 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003683 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003684 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003685 SharedsTy, CapturedStruct, IfCond,
3686 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003687 };
Alexey Bataev46978742020-01-30 10:46:11 -05003688 auto LPCRegion =
3689 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev475a7442018-01-12 19:39:11 +00003690 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003691}
3692
Alexey Bataev9f797f32015-02-05 05:57:51 +00003693void CodeGenFunction::EmitOMPTaskyieldDirective(
3694 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003695 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003696}
3697
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003698void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003699 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003700}
3701
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003702void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003703 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003704}
3705
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003706void CodeGenFunction::EmitOMPTaskgroupDirective(
3707 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003708 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3709 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003710 if (const Expr *E = S.getReductionRef()) {
3711 SmallVector<const Expr *, 4> LHSs;
3712 SmallVector<const Expr *, 4> RHSs;
3713 OMPTaskDataTy Data;
3714 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3715 auto IPriv = C->privates().begin();
3716 auto IRed = C->reduction_ops().begin();
3717 auto ILHS = C->lhs_exprs().begin();
3718 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003719 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003720 Data.ReductionVars.emplace_back(Ref);
3721 Data.ReductionCopies.emplace_back(*IPriv);
3722 Data.ReductionOps.emplace_back(*IRed);
3723 LHSs.emplace_back(*ILHS);
3724 RHSs.emplace_back(*IRHS);
3725 std::advance(IPriv, 1);
3726 std::advance(IRed, 1);
3727 std::advance(ILHS, 1);
3728 std::advance(IRHS, 1);
3729 }
3730 }
3731 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003732 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003733 LHSs, RHSs, Data);
3734 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3735 CGF.EmitVarDecl(*VD);
3736 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3737 /*Volatile=*/false, E->getType());
3738 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003739 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003740 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003741 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003742 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003743}
3744
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003745void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003746 CGM.getOpenMPRuntime().emitFlush(
3747 *this,
3748 [&S]() -> ArrayRef<const Expr *> {
3749 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3750 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3751 FlushClause->varlist_end());
3752 return llvm::None;
3753 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003754 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003755}
3756
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003757void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3758 const CodeGenLoopTy &CodeGenLoop,
3759 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003760 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003761 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3762 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003763 EmitVarDecl(*IVDecl);
3764
3765 // Emit the iterations count variable.
3766 // If it is not a variable, Sema decided to calculate iterations count on each
3767 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003768 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003769 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3770 // Emit calculation of the iterations count.
3771 EmitIgnoredExpr(S.getCalcLastIteration());
3772 }
3773
Alexey Bataevddf3db92018-04-13 17:31:06 +00003774 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003775
Carlo Bertolli962bb802017-01-03 18:24:42 +00003776 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003777 // Check pre-condition.
3778 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003779 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003780 // Skip the entire loop if we don't meet the precondition.
3781 // If the condition constant folds and can be elided, avoid emitting the
3782 // whole loop.
3783 bool CondConstant;
3784 llvm::BasicBlock *ContBlock = nullptr;
3785 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3786 if (!CondConstant)
3787 return;
3788 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003789 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003790 ContBlock = createBasicBlock("omp.precond.end");
3791 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3792 getProfileCount(&S));
3793 EmitBlock(ThenBlock);
3794 incrementProfileCounter(&S);
3795 }
3796
Alexey Bataev617db5f2017-12-04 15:38:33 +00003797 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003798 // Emit 'then' code.
3799 {
3800 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003801
3802 LValue LB = EmitOMPHelperVar(
3803 *this, cast<DeclRefExpr>(
3804 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3805 ? S.getCombinedLowerBoundVariable()
3806 : S.getLowerBoundVariable())));
3807 LValue UB = EmitOMPHelperVar(
3808 *this, cast<DeclRefExpr>(
3809 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3810 ? S.getCombinedUpperBoundVariable()
3811 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003812 LValue ST =
3813 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3814 LValue IL =
3815 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3816
3817 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003818 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003819 // Emit implicit barrier to synchronize threads and avoid data races
3820 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003821 // lastprivate variables.
3822 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003823 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003824 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003825 }
3826 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003827 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003828 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3829 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003830 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003831 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003832 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003833 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003834 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3835 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003836
3837 // Detect the distribute schedule kind and chunk.
3838 llvm::Value *Chunk = nullptr;
3839 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003840 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003841 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003842 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003843 Chunk = EmitScalarExpr(Ch);
3844 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003845 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003846 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003847 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003848 } else {
3849 // Default behaviour for dist_schedule clause.
3850 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3851 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003852 }
3853 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3854 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3855
3856 // OpenMP [2.10.8, distribute Construct, Description]
3857 // If dist_schedule is specified, kind must be static. If specified,
3858 // iterations are divided into chunks of size chunk_size, chunks are
3859 // assigned to the teams of the league in a round-robin fashion in the
3860 // order of the team number. When no chunk_size is specified, the
3861 // iteration space is divided into chunks that are approximately equal
3862 // in size, and at most one chunk is distributed to each team of the
3863 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003864 bool StaticChunked = RT.isStaticChunked(
3865 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3866 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003867 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003868 /* Chunked */ Chunk != nullptr) ||
3869 StaticChunked) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003870 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003871 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
3872 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003873 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003874 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003875 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003876 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003877 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3878 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003879 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3880 ? S.getCombinedEnsureUpperBound()
3881 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003882 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003883 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3884 ? S.getCombinedInit()
3885 : S.getInit());
3886
Alexey Bataevddf3db92018-04-13 17:31:06 +00003887 const Expr *Cond =
3888 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3889 ? S.getCombinedCond()
3890 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003891
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003892 if (StaticChunked)
3893 Cond = S.getCombinedDistCond();
3894
3895 // For static unchunked schedules generate:
3896 //
3897 // 1. For distribute alone, codegen
3898 // while (idx <= UB) {
3899 // BODY;
3900 // ++idx;
3901 // }
3902 //
3903 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3904 // while (idx <= UB) {
3905 // <CodeGen rest of pragma>(LB, UB);
3906 // idx += ST;
3907 // }
3908 //
3909 // For static chunk one schedule generate:
3910 //
3911 // while (IV <= GlobalUB) {
3912 // <CodeGen rest of pragma>(LB, UB);
3913 // LB += ST;
3914 // UB += ST;
3915 // UB = min(UB, GlobalUB);
3916 // IV = LB;
3917 // }
3918 //
Alexey Bataev779a1802019-12-06 12:21:31 -05003919 emitCommonSimdLoop(
3920 *this, S,
3921 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3922 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3923 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3924 },
3925 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
3926 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
3927 CGF.EmitOMPInnerLoop(
3928 S, LoopScope.requiresCleanups(), Cond, IncExpr,
3929 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3930 CodeGenLoop(CGF, S, LoopExit);
3931 },
3932 [&S, StaticChunked](CodeGenFunction &CGF) {
3933 if (StaticChunked) {
3934 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3935 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3936 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3937 CGF.EmitIgnoredExpr(S.getCombinedInit());
3938 }
3939 });
3940 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003941 EmitBlock(LoopExit.getBlock());
3942 // Tell the runtime we are done.
Alexey Bataevc33ba8c2020-01-17 14:05:40 -05003943 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003944 } else {
3945 // Emit the outer loop, which requests its work chunk [LB..UB] from
3946 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003947 const OMPLoopArguments LoopArguments = {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003948 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3949 IL.getAddress(*this), Chunk};
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003950 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3951 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003952 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003953 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003954 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003955 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003956 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003957 });
3958 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003959 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3960 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3961 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003962 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003963 // Emit post-update of the reduction variables if IsLastIter != 0.
3964 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003965 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003966 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003967 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003968 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003969 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003970 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003971 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003972 EmitOMPLastprivateClauseFinal(
3973 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003974 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003975 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003976 }
3977
3978 // We're now done with the loop, so jump to the continuation block.
3979 if (ContBlock) {
3980 EmitBranch(ContBlock);
3981 EmitBlock(ContBlock, true);
3982 }
3983 }
3984}
3985
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003986void CodeGenFunction::EmitOMPDistributeDirective(
3987 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003988 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003989 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003990 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003991 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003992 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003993}
3994
Alexey Bataev5f600d62015-09-29 03:48:57 +00003995static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
Alexey Bataevc33ba8c2020-01-17 14:05:40 -05003996 const CapturedStmt *S,
3997 SourceLocation Loc) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003998 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3999 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
4000 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevc33ba8c2020-01-17 14:05:40 -05004001 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004002 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00004003 return Fn;
4004}
4005
Alexey Bataev98eb6e32015-04-22 11:15:40 +00004006void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004007 if (S.hasClausesOfKind<OMPDependClause>()) {
4008 assert(!S.getAssociatedStmt() &&
4009 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00004010 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
4011 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00004012 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00004013 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00004014 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004015 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
4016 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004017 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00004018 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00004019 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4020 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevc33ba8c2020-01-17 14:05:40 -05004021 llvm::Function *OutlinedFn =
4022 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004023 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00004024 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00004025 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004026 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004027 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00004028 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00004029 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004030 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004031 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004032}
4033
Alexey Bataevb57056f2015-01-22 06:17:56 +00004034static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004035 QualType SrcType, QualType DestType,
4036 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004037 assert(CGF.hasScalarEvaluationKind(DestType) &&
4038 "DestType must have scalar evaluation kind.");
4039 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004040 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
4041 DestType, Loc)
4042 : CGF.EmitComplexToScalarConversion(
4043 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004044}
4045
4046static CodeGenFunction::ComplexPairTy
4047convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004048 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004049 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
4050 "DestType must have complex evaluation kind.");
4051 CodeGenFunction::ComplexPairTy ComplexVal;
4052 if (Val.isScalar()) {
4053 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004054 QualType DestElementType =
4055 DestType->castAs<ComplexType>()->getElementType();
4056 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
4057 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004058 ComplexVal = CodeGenFunction::ComplexPairTy(
4059 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
4060 } else {
4061 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004062 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
4063 QualType DestElementType =
4064 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004065 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004066 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004067 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004068 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004069 }
4070 return ComplexVal;
4071}
4072
Alexey Bataev5e018f92015-04-23 06:35:10 +00004073static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
4074 LValue LVal, RValue RVal) {
4075 if (LVal.isGlobalReg()) {
4076 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
4077 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00004078 CGF.EmitAtomicStore(RVal, LVal,
4079 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
4080 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004081 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004082 }
4083}
4084
Alexey Bataev8524d152016-01-21 12:35:58 +00004085void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
4086 QualType RValTy, SourceLocation Loc) {
4087 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004088 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00004089 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
4090 *this, RVal, RValTy, LVal.getType(), Loc)),
4091 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004092 break;
4093 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00004094 EmitStoreOfComplex(
4095 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004096 /*isInit=*/false);
4097 break;
4098 case TEK_Aggregate:
4099 llvm_unreachable("Must be a scalar or complex.");
4100 }
4101}
4102
Alexey Bataevddf3db92018-04-13 17:31:06 +00004103static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00004104 const Expr *X, const Expr *V,
4105 SourceLocation Loc) {
4106 // v = x;
4107 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
4108 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
4109 LValue XLValue = CGF.EmitLValue(X);
4110 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00004111 RValue Res = XLValue.isGlobalReg()
4112 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00004113 : CGF.EmitAtomicLoad(
4114 XLValue, Loc,
4115 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
4116 : llvm::AtomicOrdering::Monotonic,
4117 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00004118 // OpenMP, 2.12.6, atomic Construct
4119 // Any atomic construct with a seq_cst clause forces the atomically
4120 // performed operation to include an implicit flush operation without a
4121 // list.
4122 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004123 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00004124 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004125 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004126}
4127
Alexey Bataevddf3db92018-04-13 17:31:06 +00004128static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00004129 const Expr *X, const Expr *E,
4130 SourceLocation Loc) {
4131 // x = expr;
4132 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00004133 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004134 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
Alexey Bataevb8329262015-02-27 06:33:30 +00004135 // OpenMP, 2.12.6, atomic Construct
4136 // Any atomic construct with a seq_cst clause forces the atomically
4137 // performed operation to include an implicit flush operation without a
4138 // list.
4139 if (IsSeqCst)
4140 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4141}
4142
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00004143static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
4144 RValue Update,
4145 BinaryOperatorKind BO,
4146 llvm::AtomicOrdering AO,
4147 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004148 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004149 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00004150 // expression is simple and atomic is allowed for the given type for the
4151 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004152 if (BO == BO_Comma || !Update.isScalar() ||
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004153 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
4154 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
4155 (Update.getScalarVal()->getType() !=
4156 X.getAddress(CGF).getElementType())) ||
4157 !X.getAddress(CGF).getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004158 !Context.getTargetInfo().hasBuiltinAtomic(
4159 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00004160 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004161
4162 llvm::AtomicRMWInst::BinOp RMWOp;
4163 switch (BO) {
4164 case BO_Add:
4165 RMWOp = llvm::AtomicRMWInst::Add;
4166 break;
4167 case BO_Sub:
4168 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00004169 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004170 RMWOp = llvm::AtomicRMWInst::Sub;
4171 break;
4172 case BO_And:
4173 RMWOp = llvm::AtomicRMWInst::And;
4174 break;
4175 case BO_Or:
4176 RMWOp = llvm::AtomicRMWInst::Or;
4177 break;
4178 case BO_Xor:
4179 RMWOp = llvm::AtomicRMWInst::Xor;
4180 break;
4181 case BO_LT:
4182 RMWOp = X.getType()->hasSignedIntegerRepresentation()
4183 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
4184 : llvm::AtomicRMWInst::Max)
4185 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
4186 : llvm::AtomicRMWInst::UMax);
4187 break;
4188 case BO_GT:
4189 RMWOp = X.getType()->hasSignedIntegerRepresentation()
4190 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
4191 : llvm::AtomicRMWInst::Min)
4192 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
4193 : llvm::AtomicRMWInst::UMin);
4194 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004195 case BO_Assign:
4196 RMWOp = llvm::AtomicRMWInst::Xchg;
4197 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004198 case BO_Mul:
4199 case BO_Div:
4200 case BO_Rem:
4201 case BO_Shl:
4202 case BO_Shr:
4203 case BO_LAnd:
4204 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00004205 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004206 case BO_PtrMemD:
4207 case BO_PtrMemI:
4208 case BO_LE:
4209 case BO_GE:
4210 case BO_EQ:
4211 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004212 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004213 case BO_AddAssign:
4214 case BO_SubAssign:
4215 case BO_AndAssign:
4216 case BO_OrAssign:
4217 case BO_XorAssign:
4218 case BO_MulAssign:
4219 case BO_DivAssign:
4220 case BO_RemAssign:
4221 case BO_ShlAssign:
4222 case BO_ShrAssign:
4223 case BO_Comma:
4224 llvm_unreachable("Unsupported atomic update operation");
4225 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00004226 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004227 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
4228 UpdateVal = CGF.Builder.CreateIntCast(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004229 IC, X.getAddress(CGF).getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004230 X.getType()->hasSignedIntegerRepresentation());
4231 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00004232 llvm::Value *Res =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004233 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004234 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004235}
4236
Alexey Bataev5e018f92015-04-23 06:35:10 +00004237std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004238 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
4239 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004240 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004241 // Update expressions are allowed to have the following forms:
4242 // x binop= expr; -> xrval + expr;
4243 // x++, ++x -> xrval + 1;
4244 // x--, --x -> xrval - 1;
4245 // x = x binop expr; -> xrval binop expr
4246 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004247 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
4248 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004249 if (X.isGlobalReg()) {
4250 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
4251 // 'xrval'.
4252 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
4253 } else {
4254 // Perform compare-and-swap procedure.
4255 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004256 }
4257 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004258 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004259}
4260
Alexey Bataevddf3db92018-04-13 17:31:06 +00004261static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00004262 const Expr *X, const Expr *E,
4263 const Expr *UE, bool IsXLHSInRHSPart,
4264 SourceLocation Loc) {
4265 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4266 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004267 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004268 // Update expressions are allowed to have the following forms:
4269 // x binop= expr; -> xrval + expr;
4270 // x++, ++x -> xrval + 1;
4271 // x--, --x -> xrval - 1;
4272 // x = x binop expr; -> xrval binop expr
4273 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004274 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00004275 LValue XLValue = CGF.EmitLValue(X);
4276 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004277 llvm::AtomicOrdering AO = IsSeqCst
4278 ? llvm::AtomicOrdering::SequentiallyConsistent
4279 : llvm::AtomicOrdering::Monotonic;
4280 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4281 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4282 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4283 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4284 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
4285 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4286 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4287 return CGF.EmitAnyExpr(UE);
4288 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00004289 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
4290 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004291 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004292 // OpenMP, 2.12.6, atomic Construct
4293 // Any atomic construct with a seq_cst clause forces the atomically
4294 // performed operation to include an implicit flush operation without a
4295 // list.
4296 if (IsSeqCst)
4297 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4298}
4299
4300static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004301 QualType SourceType, QualType ResType,
4302 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004303 switch (CGF.getEvaluationKind(ResType)) {
4304 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004305 return RValue::get(
4306 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00004307 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004308 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004309 return RValue::getComplex(Res.first, Res.second);
4310 }
4311 case TEK_Aggregate:
4312 break;
4313 }
4314 llvm_unreachable("Must be a scalar or complex.");
4315}
4316
Alexey Bataevddf3db92018-04-13 17:31:06 +00004317static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004318 bool IsPostfixUpdate, const Expr *V,
4319 const Expr *X, const Expr *E,
4320 const Expr *UE, bool IsXLHSInRHSPart,
4321 SourceLocation Loc) {
4322 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4323 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4324 RValue NewVVal;
4325 LValue VLValue = CGF.EmitLValue(V);
4326 LValue XLValue = CGF.EmitLValue(X);
4327 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004328 llvm::AtomicOrdering AO = IsSeqCst
4329 ? llvm::AtomicOrdering::SequentiallyConsistent
4330 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004331 QualType NewVValType;
4332 if (UE) {
4333 // 'x' is updated with some additional value.
4334 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4335 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004336 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00004337 // Update expressions are allowed to have the following forms:
4338 // x binop= expr; -> xrval + expr;
4339 // x++, ++x -> xrval + 1;
4340 // x--, --x -> xrval - 1;
4341 // x = x binop expr; -> xrval binop expr
4342 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004343 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4344 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4345 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004346 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004347 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004348 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004349 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004350 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4351 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4352 RValue Res = CGF.EmitAnyExpr(UE);
4353 NewVVal = IsPostfixUpdate ? XRValue : Res;
4354 return Res;
4355 };
4356 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4357 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004358 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004359 if (Res.first) {
4360 // 'atomicrmw' instruction was generated.
4361 if (IsPostfixUpdate) {
4362 // Use old value from 'atomicrmw'.
4363 NewVVal = Res.second;
4364 } else {
4365 // 'atomicrmw' does not provide new value, so evaluate it using old
4366 // value of 'x'.
4367 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4368 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4369 NewVVal = CGF.EmitAnyExpr(UE);
4370 }
4371 }
4372 } else {
4373 // 'x' is simply rewritten with some 'expr'.
4374 NewVValType = X->getType().getNonReferenceType();
4375 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004376 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004377 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004378 NewVVal = XRValue;
4379 return ExprRValue;
4380 };
4381 // Try to perform atomicrmw xchg, otherwise simple exchange.
4382 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4383 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4384 Loc, Gen);
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004385 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004386 if (Res.first) {
4387 // 'atomicrmw' instruction was generated.
4388 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4389 }
4390 }
4391 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00004392 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevf117f2c2020-01-28 11:19:45 -05004393 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004394 // OpenMP, 2.12.6, atomic Construct
4395 // Any atomic construct with a seq_cst clause forces the atomically
4396 // performed operation to include an implicit flush operation without a
4397 // list.
4398 if (IsSeqCst)
4399 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4400}
4401
Alexey Bataevddf3db92018-04-13 17:31:06 +00004402static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004403 bool IsSeqCst, bool IsPostfixUpdate,
4404 const Expr *X, const Expr *V, const Expr *E,
4405 const Expr *UE, bool IsXLHSInRHSPart,
4406 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004407 switch (Kind) {
4408 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004409 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004410 break;
4411 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004412 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004413 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004414 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004415 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004416 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004417 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004418 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004419 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004420 IsXLHSInRHSPart, Loc);
4421 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004422 case OMPC_if:
4423 case OMPC_final:
4424 case OMPC_num_threads:
4425 case OMPC_private:
4426 case OMPC_firstprivate:
4427 case OMPC_lastprivate:
4428 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004429 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004430 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004431 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004432 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004433 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004434 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004435 case OMPC_collapse:
4436 case OMPC_default:
4437 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -05004438 case OMPC_acq_rel:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004439 case OMPC_shared:
4440 case OMPC_linear:
4441 case OMPC_aligned:
4442 case OMPC_copyin:
4443 case OMPC_copyprivate:
4444 case OMPC_flush:
4445 case OMPC_proc_bind:
4446 case OMPC_schedule:
4447 case OMPC_ordered:
4448 case OMPC_nowait:
4449 case OMPC_untied:
4450 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004451 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004452 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004453 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004454 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004455 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004456 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004457 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004458 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004459 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004460 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004461 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004462 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004463 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004464 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004465 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004466 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004467 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004468 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004469 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004470 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004471 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004472 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004473 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004474 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004475 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004476 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004477 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -05004478 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -05004479 case OMPC_order:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004480 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4481 }
4482}
4483
4484void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004485 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004486 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004487 for (const OMPClause *C : S.clauses()) {
Alexey Bataevea9166b2020-02-06 16:30:23 -05004488 // Find first clause (skip seq_cst|acq_rel clause, if it is first).
4489 if (C->getClauseKind() != OMPC_seq_cst &&
4490 C->getClauseKind() != OMPC_acq_rel) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004491 Kind = C->getClauseKind();
4492 break;
4493 }
4494 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004495
Alexey Bataevddf3db92018-04-13 17:31:06 +00004496 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004497 if (const auto *FE = dyn_cast<FullExpr>(CS))
4498 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004499 // Processing for statements under 'atomic capture'.
4500 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004501 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004502 if (const auto *FE = dyn_cast<FullExpr>(C))
4503 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004504 }
4505 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004506
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004507 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4508 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004509 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004510 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004511 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004512 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004513 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004514 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004515 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004516}
4517
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004518static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4519 const OMPExecutableDirective &S,
4520 const RegionCodeGenTy &CodeGen) {
4521 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4522 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004523
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004524 // On device emit this construct as inlined code.
4525 if (CGM.getLangOpts().OpenMPIsDevice) {
4526 OMPLexicalScope Scope(CGF, S, OMPD_target);
4527 CGM.getOpenMPRuntime().emitInlinedDirective(
4528 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004529 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004530 });
4531 return;
4532 }
4533
Alexey Bataev46978742020-01-30 10:46:11 -05004534 auto LPCRegion =
4535 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004536 llvm::Function *Fn = nullptr;
4537 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004538
Samuel Antaobed3c462015-10-02 16:14:20 +00004539 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004540 // Check for the at most one if clause associated with the target region.
4541 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4542 if (C->getNameModifier() == OMPD_unknown ||
4543 C->getNameModifier() == OMPD_target) {
4544 IfCond = C->getCondition();
4545 break;
4546 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004547 }
4548
4549 // Check if we have any device clause associated with the directive.
4550 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004551 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004552 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004553
Samuel Antaoee8fb302016-01-06 13:42:12 +00004554 // Check if we have an if clause whose conditional always evaluates to false
4555 // or if we do not have any targets specified. If so the target region is not
4556 // an offload entry point.
4557 bool IsOffloadEntry = true;
4558 if (IfCond) {
4559 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004560 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004561 IsOffloadEntry = false;
4562 }
4563 if (CGM.getLangOpts().OMPTargetTriples.empty())
4564 IsOffloadEntry = false;
4565
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004566 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004567 StringRef ParentName;
4568 // In case we have Ctors/Dtors we use the complete type variant to produce
4569 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004570 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004571 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004572 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004573 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4574 else
4575 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004576 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004577
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004578 // Emit target region as a standalone region.
4579 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4580 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004581 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004582 auto &&SizeEmitter =
4583 [IsOffloadEntry](CodeGenFunction &CGF,
4584 const OMPLoopDirective &D) -> llvm::Value * {
4585 if (IsOffloadEntry) {
4586 OMPLoopScope(CGF, D);
4587 // Emit calculation of the iterations count.
4588 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4589 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4590 /*isSigned=*/false);
4591 return NumIterations;
4592 }
4593 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004594 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004595 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4596 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004597}
4598
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004599static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4600 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004601 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004602 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4603 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4604 CGF.EmitOMPPrivateClause(S, PrivateScope);
4605 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004606 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4607 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004608
Alexey Bataev475a7442018-01-12 19:39:11 +00004609 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004610}
4611
4612void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4613 StringRef ParentName,
4614 const OMPTargetDirective &S) {
4615 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4616 emitTargetRegion(CGF, S, Action);
4617 };
4618 llvm::Function *Fn;
4619 llvm::Constant *Addr;
4620 // Emit target region as a standalone region.
4621 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4622 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4623 assert(Fn && Addr && "Target device function emission failed.");
4624}
4625
4626void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4627 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4628 emitTargetRegion(CGF, S, Action);
4629 };
4630 emitCommonOMPTargetDirective(*this, S, CodeGen);
4631}
4632
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004633static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4634 const OMPExecutableDirective &S,
4635 OpenMPDirectiveKind InnermostKind,
4636 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004637 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004638 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004639 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4640 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004641
Alexey Bataevddf3db92018-04-13 17:31:06 +00004642 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4643 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004644 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004645 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4646 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004647
Carlo Bertollic6872252016-04-04 15:55:02 +00004648 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004649 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004650 }
4651
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004652 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004653 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4654 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004655 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004656 CapturedVars);
4657}
4658
4659void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004660 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004661 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004662 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004663 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004664 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4665 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004666 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004667 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004668 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004669 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004670 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004671 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004672 emitPostUpdateForReductionClause(*this, S,
4673 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004674}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004675
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004676static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4677 const OMPTargetTeamsDirective &S) {
4678 auto *CS = S.getCapturedStmt(OMPD_teams);
4679 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004680 // Emit teams region as a standalone region.
4681 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004682 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004683 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4684 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4685 CGF.EmitOMPPrivateClause(S, PrivateScope);
4686 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4687 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004688 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4689 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004690 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004691 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004692 };
4693 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004694 emitPostUpdateForReductionClause(CGF, S,
4695 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004696}
4697
4698void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4699 CodeGenModule &CGM, StringRef ParentName,
4700 const OMPTargetTeamsDirective &S) {
4701 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4702 emitTargetTeamsRegion(CGF, Action, S);
4703 };
4704 llvm::Function *Fn;
4705 llvm::Constant *Addr;
4706 // Emit target region as a standalone region.
4707 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4708 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4709 assert(Fn && Addr && "Target device function emission failed.");
4710}
4711
4712void CodeGenFunction::EmitOMPTargetTeamsDirective(
4713 const OMPTargetTeamsDirective &S) {
4714 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4715 emitTargetTeamsRegion(CGF, Action, S);
4716 };
4717 emitCommonOMPTargetDirective(*this, S, CodeGen);
4718}
4719
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004720static void
4721emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4722 const OMPTargetTeamsDistributeDirective &S) {
4723 Action.Enter(CGF);
4724 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4725 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4726 };
4727
4728 // Emit teams region as a standalone region.
4729 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004730 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004731 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004732 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4733 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4734 (void)PrivateScope.Privatize();
4735 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4736 CodeGenDistribute);
4737 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4738 };
4739 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4740 emitPostUpdateForReductionClause(CGF, S,
4741 [](CodeGenFunction &) { return nullptr; });
4742}
4743
4744void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4745 CodeGenModule &CGM, StringRef ParentName,
4746 const OMPTargetTeamsDistributeDirective &S) {
4747 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4748 emitTargetTeamsDistributeRegion(CGF, Action, S);
4749 };
4750 llvm::Function *Fn;
4751 llvm::Constant *Addr;
4752 // Emit target region as a standalone region.
4753 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4754 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4755 assert(Fn && Addr && "Target device function emission failed.");
4756}
4757
4758void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4759 const OMPTargetTeamsDistributeDirective &S) {
4760 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4761 emitTargetTeamsDistributeRegion(CGF, Action, S);
4762 };
4763 emitCommonOMPTargetDirective(*this, S, CodeGen);
4764}
4765
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004766static void emitTargetTeamsDistributeSimdRegion(
4767 CodeGenFunction &CGF, PrePostActionTy &Action,
4768 const OMPTargetTeamsDistributeSimdDirective &S) {
4769 Action.Enter(CGF);
4770 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4771 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4772 };
4773
4774 // Emit teams region as a standalone region.
4775 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004776 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004777 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004778 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4779 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4780 (void)PrivateScope.Privatize();
4781 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4782 CodeGenDistribute);
4783 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4784 };
4785 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4786 emitPostUpdateForReductionClause(CGF, S,
4787 [](CodeGenFunction &) { return nullptr; });
4788}
4789
4790void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4791 CodeGenModule &CGM, StringRef ParentName,
4792 const OMPTargetTeamsDistributeSimdDirective &S) {
4793 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4794 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4795 };
4796 llvm::Function *Fn;
4797 llvm::Constant *Addr;
4798 // Emit target region as a standalone region.
4799 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4800 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4801 assert(Fn && Addr && "Target device function emission failed.");
4802}
4803
4804void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4805 const OMPTargetTeamsDistributeSimdDirective &S) {
4806 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4807 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4808 };
4809 emitCommonOMPTargetDirective(*this, S, CodeGen);
4810}
4811
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004812void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4813 const OMPTeamsDistributeDirective &S) {
4814
4815 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4816 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4817 };
4818
4819 // Emit teams region as a standalone region.
4820 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004821 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004822 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004823 OMPPrivateScope PrivateScope(CGF);
4824 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4825 (void)PrivateScope.Privatize();
4826 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4827 CodeGenDistribute);
4828 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4829 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004830 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004831 emitPostUpdateForReductionClause(*this, S,
4832 [](CodeGenFunction &) { return nullptr; });
4833}
4834
Alexey Bataev999277a2017-12-06 14:31:09 +00004835void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4836 const OMPTeamsDistributeSimdDirective &S) {
4837 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4838 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4839 };
4840
4841 // Emit teams region as a standalone region.
4842 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004843 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004844 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004845 OMPPrivateScope PrivateScope(CGF);
4846 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4847 (void)PrivateScope.Privatize();
4848 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4849 CodeGenDistribute);
4850 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4851 };
4852 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4853 emitPostUpdateForReductionClause(*this, S,
4854 [](CodeGenFunction &) { return nullptr; });
4855}
4856
Carlo Bertolli62fae152017-11-20 20:46:39 +00004857void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4858 const OMPTeamsDistributeParallelForDirective &S) {
4859 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4860 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4861 S.getDistInc());
4862 };
4863
4864 // Emit teams region as a standalone region.
4865 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004866 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004867 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004868 OMPPrivateScope PrivateScope(CGF);
4869 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4870 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004871 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4872 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004873 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4874 };
4875 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4876 emitPostUpdateForReductionClause(*this, S,
4877 [](CodeGenFunction &) { return nullptr; });
4878}
4879
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004880void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4881 const OMPTeamsDistributeParallelForSimdDirective &S) {
4882 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4883 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4884 S.getDistInc());
4885 };
4886
4887 // Emit teams region as a standalone region.
4888 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004889 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004890 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004891 OMPPrivateScope PrivateScope(CGF);
4892 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4893 (void)PrivateScope.Privatize();
4894 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4895 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4896 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4897 };
Alexey Bataev0b978942019-12-11 15:26:38 -05004898 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
4899 CodeGen);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004900 emitPostUpdateForReductionClause(*this, S,
4901 [](CodeGenFunction &) { return nullptr; });
4902}
4903
Carlo Bertolli52978c32018-01-03 21:12:44 +00004904static void emitTargetTeamsDistributeParallelForRegion(
4905 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4906 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004907 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004908 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4909 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4910 S.getDistInc());
4911 };
4912
4913 // Emit teams region as a standalone region.
4914 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004915 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004916 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004917 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4918 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4919 (void)PrivateScope.Privatize();
4920 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4921 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4922 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4923 };
4924
4925 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4926 CodeGenTeams);
4927 emitPostUpdateForReductionClause(CGF, S,
4928 [](CodeGenFunction &) { return nullptr; });
4929}
4930
4931void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4932 CodeGenModule &CGM, StringRef ParentName,
4933 const OMPTargetTeamsDistributeParallelForDirective &S) {
4934 // Emit SPMD target teams distribute parallel for region as a standalone
4935 // region.
4936 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4937 emitTargetTeamsDistributeParallelForRegion(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::EmitOMPTargetTeamsDistributeParallelForDirective(
4948 const OMPTargetTeamsDistributeParallelForDirective &S) {
4949 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4950 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4951 };
4952 emitCommonOMPTargetDirective(*this, S, CodeGen);
4953}
4954
Alexey Bataev647dd842018-01-15 20:59:40 +00004955static void emitTargetTeamsDistributeParallelForSimdRegion(
4956 CodeGenFunction &CGF,
4957 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4958 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004959 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004960 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4961 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4962 S.getDistInc());
4963 };
4964
4965 // Emit teams region as a standalone region.
4966 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004967 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004968 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004969 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4970 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4971 (void)PrivateScope.Privatize();
4972 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4973 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4974 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4975 };
4976
4977 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4978 CodeGenTeams);
4979 emitPostUpdateForReductionClause(CGF, S,
4980 [](CodeGenFunction &) { return nullptr; });
4981}
4982
4983void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4984 CodeGenModule &CGM, StringRef ParentName,
4985 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4986 // Emit SPMD target teams distribute parallel for simd region as a standalone
4987 // region.
4988 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4989 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4990 };
4991 llvm::Function *Fn;
4992 llvm::Constant *Addr;
4993 // Emit target region as a standalone region.
4994 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4995 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4996 assert(Fn && Addr && "Target device function emission failed.");
4997}
4998
4999void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
5000 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
5001 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5002 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
5003 };
5004 emitCommonOMPTargetDirective(*this, S, CodeGen);
5005}
5006
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005007void CodeGenFunction::EmitOMPCancellationPointDirective(
5008 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005009 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00005010 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005011}
5012
Alexey Bataev80909872015-07-02 11:25:17 +00005013void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005014 const Expr *IfCond = nullptr;
5015 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5016 if (C->getNameModifier() == OMPD_unknown ||
5017 C->getNameModifier() == OMPD_cancel) {
5018 IfCond = C->getCondition();
5019 break;
5020 }
5021 }
Johannes Doerfert10fedd92019-12-26 11:23:38 -06005022 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
5023 // TODO: This check is necessary as we only generate `omp parallel` through
5024 // the OpenMPIRBuilder for now.
5025 if (S.getCancelRegion() == OMPD_parallel) {
5026 llvm::Value *IfCondition = nullptr;
5027 if (IfCond)
5028 IfCondition = EmitScalarExpr(IfCond,
5029 /*IgnoreResultAssign=*/true);
5030 return Builder.restoreIP(
5031 OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion()));
5032 }
5033 }
5034
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005035 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005036 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00005037}
5038
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005039CodeGenFunction::JumpDest
5040CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00005041 if (Kind == OMPD_parallel || Kind == OMPD_task ||
5042 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005043 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005044 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00005045 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
5046 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00005047 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00005048 Kind == OMPD_teams_distribute_parallel_for ||
5049 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00005050 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005051}
Michael Wong65f367f2015-07-21 13:44:28 +00005052
Samuel Antaocc10b852016-07-28 14:23:26 +00005053void CodeGenFunction::EmitOMPUseDevicePtrClause(
5054 const OMPClause &NC, OMPPrivateScope &PrivateScope,
5055 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
5056 const auto &C = cast<OMPUseDevicePtrClause>(NC);
5057 auto OrigVarIt = C.varlist_begin();
5058 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005059 for (const Expr *PvtVarIt : C.private_copies()) {
5060 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
5061 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
5062 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00005063
5064 // In order to identify the right initializer we need to match the
5065 // declaration used by the mapping logic. In some cases we may get
5066 // OMPCapturedExprDecl that refers to the original declaration.
5067 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005068 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005069 // OMPCapturedExprDecl are used to privative fields of the current
5070 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00005071 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00005072 assert(isa<CXXThisExpr>(ME->getBase()) &&
5073 "Base should be the current struct!");
5074 MatchingVD = ME->getMemberDecl();
5075 }
5076
5077 // If we don't have information about the current list item, move on to
5078 // the next one.
5079 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
5080 if (InitAddrIt == CaptureDeviceAddrMap.end())
5081 continue;
5082
Alexey Bataevddf3db92018-04-13 17:31:06 +00005083 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
5084 InitAddrIt, InitVD,
5085 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00005086 // Initialize the temporary initialization variable with the address we
5087 // get from the runtime library. We have to cast the source address
5088 // because it is always a void *. References are materialized in the
5089 // privatization scope, so the initialization here disregards the fact
5090 // the original variable is a reference.
5091 QualType AddrQTy =
5092 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
5093 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
5094 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
5095 setAddrOfLocalVar(InitVD, InitAddr);
5096
5097 // Emit private declaration, it will be initialized by the value we
5098 // declaration we just added to the local declarations map.
5099 EmitDecl(*PvtVD);
5100
5101 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005102 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00005103 LocalDeclMap.erase(InitVD);
5104
5105 // Return the address of the private variable.
5106 return GetAddrOfLocalVar(PvtVD);
5107 });
5108 assert(IsRegistered && "firstprivate var already registered as private");
5109 // Silence the warning about unused variable.
5110 (void)IsRegistered;
5111
5112 ++OrigVarIt;
5113 ++InitIt;
5114 }
5115}
5116
Michael Wong65f367f2015-07-21 13:44:28 +00005117// Generate the instructions for '#pragma omp target data' directive.
5118void CodeGenFunction::EmitOMPTargetDataDirective(
5119 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005120 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
5121
5122 // Create a pre/post action to signal the privatization of the device pointer.
5123 // This action can be replaced by the OpenMP runtime code generation to
5124 // deactivate privatization.
5125 bool PrivatizeDevicePointers = false;
5126 class DevicePointerPrivActionTy : public PrePostActionTy {
5127 bool &PrivatizeDevicePointers;
5128
5129 public:
5130 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
5131 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
5132 void Enter(CodeGenFunction &CGF) override {
5133 PrivatizeDevicePointers = true;
5134 }
Samuel Antaodf158d52016-04-27 22:58:19 +00005135 };
Samuel Antaocc10b852016-07-28 14:23:26 +00005136 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
5137
5138 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00005139 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005140 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00005141 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00005142 };
5143
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005144 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00005145 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
5146 &InnermostCodeGen](CodeGenFunction &CGF,
5147 PrePostActionTy &Action) {
5148 RegionCodeGenTy RCG(InnermostCodeGen);
5149 PrivatizeDevicePointers = false;
5150
5151 // Call the pre-action to change the status of PrivatizeDevicePointers if
5152 // needed.
5153 Action.Enter(CGF);
5154
5155 if (PrivatizeDevicePointers) {
5156 OMPPrivateScope PrivateScope(CGF);
5157 // Emit all instances of the use_device_ptr clause.
5158 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
5159 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
5160 Info.CaptureDeviceAddrMap);
5161 (void)PrivateScope.Privatize();
5162 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005163 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00005164 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005165 }
Samuel Antaocc10b852016-07-28 14:23:26 +00005166 };
5167
5168 // Forward the provided action to the privatization codegen.
5169 RegionCodeGenTy PrivRCG(PrivCodeGen);
5170 PrivRCG.setAction(Action);
5171
5172 // Notwithstanding the body of the region is emitted as inlined directive,
5173 // we don't use an inline scope as changes in the references inside the
5174 // region are expected to be visible outside, so we do not privative them.
5175 OMPLexicalScope Scope(CGF, S);
5176 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
5177 PrivRCG);
5178 };
5179
5180 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00005181
5182 // If we don't have target devices, don't bother emitting the data mapping
5183 // code.
5184 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005185 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00005186 return;
5187 }
5188
5189 // Check if we have any if clause associated with the directive.
5190 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005191 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00005192 IfCond = C->getCondition();
5193
5194 // Check if we have any device clause associated with the directive.
5195 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005196 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00005197 Device = C->getDevice();
5198
Samuel Antaocc10b852016-07-28 14:23:26 +00005199 // Set the action to signal privatization of device pointers.
5200 RCG.setAction(PrivAction);
5201
5202 // Emit region code.
5203 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
5204 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00005205}
Alexey Bataev49f6e782015-12-01 04:18:41 +00005206
Samuel Antaodf67fc42016-01-19 19:15:56 +00005207void CodeGenFunction::EmitOMPTargetEnterDataDirective(
5208 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005209 // If we don't have target devices, don't bother emitting the data mapping
5210 // code.
5211 if (CGM.getLangOpts().OMPTargetTriples.empty())
5212 return;
5213
5214 // Check if we have any if clause associated with the directive.
5215 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005216 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005217 IfCond = C->getCondition();
5218
5219 // Check if we have any device clause associated with the directive.
5220 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005221 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005222 Device = C->getDevice();
5223
Alexey Bataev475a7442018-01-12 19:39:11 +00005224 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005225 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005226}
5227
Samuel Antao72590762016-01-19 20:04:50 +00005228void CodeGenFunction::EmitOMPTargetExitDataDirective(
5229 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00005230 // If we don't have target devices, don't bother emitting the data mapping
5231 // code.
5232 if (CGM.getLangOpts().OMPTargetTriples.empty())
5233 return;
5234
5235 // Check if we have any if clause associated with the directive.
5236 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005237 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00005238 IfCond = C->getCondition();
5239
5240 // Check if we have any device clause associated with the directive.
5241 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005242 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00005243 Device = C->getDevice();
5244
Alexey Bataev475a7442018-01-12 19:39:11 +00005245 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005246 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00005247}
5248
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005249static void emitTargetParallelRegion(CodeGenFunction &CGF,
5250 const OMPTargetParallelDirective &S,
5251 PrePostActionTy &Action) {
5252 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00005253 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005254 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00005255 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005256 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005257 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5258 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5259 CGF.EmitOMPPrivateClause(S, PrivateScope);
5260 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5261 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00005262 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5263 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005264 // TODO: Add support for clauses.
5265 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005266 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005267 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00005268 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
5269 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005270 emitPostUpdateForReductionClause(CGF, S,
5271 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005272}
5273
5274void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
5275 CodeGenModule &CGM, StringRef ParentName,
5276 const OMPTargetParallelDirective &S) {
5277 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5278 emitTargetParallelRegion(CGF, S, Action);
5279 };
5280 llvm::Function *Fn;
5281 llvm::Constant *Addr;
5282 // Emit target region as a standalone region.
5283 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5284 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5285 assert(Fn && Addr && "Target device function emission failed.");
5286}
5287
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005288void CodeGenFunction::EmitOMPTargetParallelDirective(
5289 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005290 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5291 emitTargetParallelRegion(CGF, S, Action);
5292 };
5293 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005294}
5295
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005296static void emitTargetParallelForRegion(CodeGenFunction &CGF,
5297 const OMPTargetParallelForDirective &S,
5298 PrePostActionTy &Action) {
5299 Action.Enter(CGF);
5300 // Emit directive as a combined directive that consists of two implicit
5301 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005302 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5303 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00005304 CodeGenFunction::OMPCancelStackRAII CancelRegion(
5305 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005306 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5307 emitDispatchForLoopBounds);
5308 };
5309 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
5310 emitEmptyBoundParameters);
5311}
5312
5313void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
5314 CodeGenModule &CGM, StringRef ParentName,
5315 const OMPTargetParallelForDirective &S) {
5316 // Emit SPMD target parallel for region as a standalone region.
5317 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5318 emitTargetParallelForRegion(CGF, S, Action);
5319 };
5320 llvm::Function *Fn;
5321 llvm::Constant *Addr;
5322 // Emit target region as a standalone region.
5323 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5324 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5325 assert(Fn && Addr && "Target device function emission failed.");
5326}
5327
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005328void CodeGenFunction::EmitOMPTargetParallelForDirective(
5329 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005330 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5331 emitTargetParallelForRegion(CGF, S, Action);
5332 };
5333 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005334}
5335
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005336static void
5337emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5338 const OMPTargetParallelForSimdDirective &S,
5339 PrePostActionTy &Action) {
5340 Action.Enter(CGF);
5341 // Emit directive as a combined directive that consists of two implicit
5342 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005343 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5344 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005345 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5346 emitDispatchForLoopBounds);
5347 };
5348 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5349 emitEmptyBoundParameters);
5350}
5351
5352void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5353 CodeGenModule &CGM, StringRef ParentName,
5354 const OMPTargetParallelForSimdDirective &S) {
5355 // Emit SPMD target parallel for region as a standalone region.
5356 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5357 emitTargetParallelForSimdRegion(CGF, S, Action);
5358 };
5359 llvm::Function *Fn;
5360 llvm::Constant *Addr;
5361 // Emit target region as a standalone region.
5362 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5363 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5364 assert(Fn && Addr && "Target device function emission failed.");
5365}
5366
5367void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5368 const OMPTargetParallelForSimdDirective &S) {
5369 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5370 emitTargetParallelForSimdRegion(CGF, S, Action);
5371 };
5372 emitCommonOMPTargetDirective(*this, S, CodeGen);
5373}
5374
Alexey Bataev7292c292016-04-25 12:22:29 +00005375/// Emit a helper variable and return corresponding lvalue.
5376static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5377 const ImplicitParamDecl *PVD,
5378 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005379 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5380 Privates.addPrivate(VDecl,
5381 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00005382}
5383
5384void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5385 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5386 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00005387 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005388 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5389 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005390 const Expr *IfCond = nullptr;
5391 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5392 if (C->getNameModifier() == OMPD_unknown ||
5393 C->getNameModifier() == OMPD_taskloop) {
5394 IfCond = C->getCondition();
5395 break;
5396 }
5397 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005398
5399 OMPTaskDataTy Data;
5400 // Check if taskloop must be emitted without taskgroup.
5401 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00005402 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005403 Data.Tied = true;
5404 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005405 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5406 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005407 Data.Schedule.setInt(/*IntVal=*/false);
5408 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005409 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5410 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005411 Data.Schedule.setInt(/*IntVal=*/true);
5412 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005413 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005414
5415 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5416 // if (PreCond) {
5417 // for (IV in 0..LastIteration) BODY;
5418 // <Final counter/linear vars updates>;
5419 // }
5420 //
5421
5422 // Emit: if (PreCond) - begin.
5423 // If the condition constant folds and can be elided, avoid emitting the
5424 // whole loop.
5425 bool CondConstant;
5426 llvm::BasicBlock *ContBlock = nullptr;
5427 OMPLoopScope PreInitScope(CGF, S);
5428 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5429 if (!CondConstant)
5430 return;
5431 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005432 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005433 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5434 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5435 CGF.getProfileCount(&S));
5436 CGF.EmitBlock(ThenBlock);
5437 CGF.incrementProfileCounter(&S);
5438 }
5439
Alexey Bataev61205822019-12-04 09:50:21 -05005440 (void)CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005441
Alexey Bataev7292c292016-04-25 12:22:29 +00005442 OMPPrivateScope LoopScope(CGF);
5443 // Emit helper vars inits.
5444 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5445 auto *I = CS->getCapturedDecl()->param_begin();
5446 auto *LBP = std::next(I, LowerBound);
5447 auto *UBP = std::next(I, UpperBound);
5448 auto *STP = std::next(I, Stride);
5449 auto *LIP = std::next(I, LastIter);
5450 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5451 LoopScope);
5452 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5453 LoopScope);
5454 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5455 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5456 LoopScope);
5457 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005458 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005459 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005460 (void)LoopScope.Privatize();
5461 // Emit the loop iteration variable.
5462 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005463 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005464 CGF.EmitVarDecl(*IVDecl);
5465 CGF.EmitIgnoredExpr(S.getInit());
5466
5467 // Emit the iterations count variable.
5468 // If it is not a variable, Sema decided to calculate iterations count on
5469 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005470 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005471 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5472 // Emit calculation of the iterations count.
5473 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5474 }
5475
Alexey Bataev61205822019-12-04 09:50:21 -05005476 {
5477 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
5478 emitCommonSimdLoop(
5479 CGF, S,
5480 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5481 if (isOpenMPSimdDirective(S.getDirectiveKind()))
5482 CGF.EmitOMPSimdInit(S);
5483 },
5484 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
5485 CGF.EmitOMPInnerLoop(
5486 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
5487 [&S](CodeGenFunction &CGF) {
5488 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
5489 CGF.EmitStopPoint(&S);
5490 },
5491 [](CodeGenFunction &) {});
5492 });
5493 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005494 // Emit: if (PreCond) - end.
5495 if (ContBlock) {
5496 CGF.EmitBranch(ContBlock);
5497 CGF.EmitBlock(ContBlock, true);
5498 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005499 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5500 if (HasLastprivateClause) {
5501 CGF.EmitOMPLastprivateClauseFinal(
5502 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5503 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5504 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005505 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005506 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04005507 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5508 return CGF.Builder.CreateIsNotNull(
5509 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5510 (*LIP)->getType(), S.getBeginLoc()));
5511 });
Alexey Bataev7292c292016-04-25 12:22:29 +00005512 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005513 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005514 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005515 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005516 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5517 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005518 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005519 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005520 OutlinedFn, SharedsTy,
5521 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005522 };
5523 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5524 CodeGen);
5525 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005526 if (Data.Nogroup) {
5527 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5528 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005529 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5530 *this,
5531 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5532 PrePostActionTy &Action) {
5533 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005534 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5535 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005536 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005537 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005538 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005539}
5540
Alexey Bataev49f6e782015-12-01 04:18:41 +00005541void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev46978742020-01-30 10:46:11 -05005542 auto LPCRegion =
5543 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev7292c292016-04-25 12:22:29 +00005544 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005545}
5546
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005547void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5548 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev46978742020-01-30 10:46:11 -05005549 auto LPCRegion =
5550 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev61205822019-12-04 09:50:21 -05005551 OMPLexicalScope Scope(*this, S);
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005552 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005553}
Samuel Antao686c70c2016-05-26 17:30:50 +00005554
Alexey Bataev60e51c42019-10-10 20:13:02 +00005555void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5556 const OMPMasterTaskLoopDirective &S) {
5557 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5558 Action.Enter(CGF);
5559 EmitOMPTaskLoopBasedDirective(S);
5560 };
Alexey Bataev46978742020-01-30 10:46:11 -05005561 auto LPCRegion =
5562 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev60e51c42019-10-10 20:13:02 +00005563 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5564 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5565}
5566
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005567void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5568 const OMPMasterTaskLoopSimdDirective &S) {
5569 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5570 Action.Enter(CGF);
5571 EmitOMPTaskLoopBasedDirective(S);
5572 };
Alexey Bataev46978742020-01-30 10:46:11 -05005573 auto LPCRegion =
5574 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev61205822019-12-04 09:50:21 -05005575 OMPLexicalScope Scope(*this, S);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005576 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5577}
5578
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005579void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5580 const OMPParallelMasterTaskLoopDirective &S) {
5581 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5582 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5583 PrePostActionTy &Action) {
5584 Action.Enter(CGF);
5585 CGF.EmitOMPTaskLoopBasedDirective(S);
5586 };
5587 OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5588 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5589 S.getBeginLoc());
5590 };
Alexey Bataev46978742020-01-30 10:46:11 -05005591 auto LPCRegion =
5592 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005593 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5594 emitEmptyBoundParameters);
5595}
5596
Alexey Bataev14a388f2019-10-25 10:27:13 -04005597void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5598 const OMPParallelMasterTaskLoopSimdDirective &S) {
5599 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5600 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5601 PrePostActionTy &Action) {
5602 Action.Enter(CGF);
5603 CGF.EmitOMPTaskLoopBasedDirective(S);
5604 };
5605 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5606 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5607 S.getBeginLoc());
5608 };
Alexey Bataev46978742020-01-30 10:46:11 -05005609 auto LPCRegion =
5610 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005611 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5612 emitEmptyBoundParameters);
5613}
5614
Samuel Antao686c70c2016-05-26 17:30:50 +00005615// Generate the instructions for '#pragma omp target update' directive.
5616void CodeGenFunction::EmitOMPTargetUpdateDirective(
5617 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005618 // If we don't have target devices, don't bother emitting the data mapping
5619 // code.
5620 if (CGM.getLangOpts().OMPTargetTriples.empty())
5621 return;
5622
5623 // Check if we have any if clause associated with the directive.
5624 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005625 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005626 IfCond = C->getCondition();
5627
5628 // Check if we have any device clause associated with the directive.
5629 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005630 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005631 Device = C->getDevice();
5632
Alexey Bataev475a7442018-01-12 19:39:11 +00005633 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005634 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005635}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005636
5637void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5638 const OMPExecutableDirective &D) {
5639 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5640 return;
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08005641 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005642 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5643 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5644 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005645 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005646 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005647 for (const Expr *E : LD->counters()) {
Simon Pilgrim93431f92020-01-11 16:00:17 +00005648 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005649 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5650 LValue GlobLVal = CGF.EmitLValue(E);
5651 LoopGlobals.addPrivate(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08005652 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005653 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005654 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005655 // Emit only those that were not explicitly referenced in clauses.
5656 if (!CGF.LocalDeclMap.count(VD))
5657 CGF.EmitVarDecl(*VD);
5658 }
5659 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005660 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5661 if (!C->getNumForLoops())
5662 continue;
5663 for (unsigned I = LD->getCollapsedNumber(),
5664 E = C->getLoopNumIterations().size();
5665 I < E; ++I) {
5666 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005667 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005668 // Emit only those that were not explicitly referenced in clauses.
5669 if (!CGF.LocalDeclMap.count(VD))
5670 CGF.EmitVarDecl(*VD);
5671 }
5672 }
5673 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005674 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005675 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005676 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005677 }
5678 };
Alexey Bataev46978742020-01-30 10:46:11 -05005679 {
5680 auto LPCRegion =
5681 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
5682 OMPSimdLexicalScope Scope(*this, D);
5683 CGM.getOpenMPRuntime().emitInlinedDirective(
5684 *this,
5685 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5686 : D.getDirectiveKind(),
5687 CodeGen);
5688 }
5689 // Check for outer lastprivate conditional update.
5690 checkForLastprivateConditionalUpdate(*this, D);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005691}