blob: 2590b2605abb785041c75724d1c1b8b58e1c4a32 [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 Bataev9959db52014-05-06 10:08:46 +000021#include "clang/AST/Stmt.h"
22#include "clang/AST/StmtOpenMP.h"
Alexey Bataev8bbf2e32019-11-04 09:59:11 -050023#include "clang/Basic/PrettyStackTrace.h"
Johannes Doerfert10fedd92019-12-26 11:23:38 -060024#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025using namespace clang;
26using namespace CodeGen;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060027using namespace llvm::omp;
Alexey Bataev9959db52014-05-06 10:08:46 +000028
Alexey Bataev3392d762016-02-16 11:18:12 +000029namespace {
30/// Lexical scope for OpenMP executable constructs, that handles correct codegen
31/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000032class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000033 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
34 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000035 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
36 if (const auto *PreInit =
37 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000038 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000039 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000040 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000041 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000042 CodeGenFunction::AutoVarEmission Emission =
43 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
44 CGF.EmitAutoVarCleanups(Emission);
45 }
46 }
Alexey Bataev3392d762016-02-16 11:18:12 +000047 }
48 }
49 }
50 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000051 CodeGenFunction::OMPPrivateScope InlinedShareds;
52
53 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
54 return CGF.LambdaCaptureFields.lookup(VD) ||
55 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
56 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
57 }
Alexey Bataev3392d762016-02-16 11:18:12 +000058
Alexey Bataev3392d762016-02-16 11:18:12 +000059public:
Alexey Bataev475a7442018-01-12 19:39:11 +000060 OMPLexicalScope(
61 CodeGenFunction &CGF, const OMPExecutableDirective &S,
62 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
63 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000064 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
65 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000066 if (EmitPreInitStmt)
67 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000068 if (!CapturedRegion.hasValue())
69 return;
70 assert(S.hasAssociatedStmt() &&
71 "Expected associated statement for inlined directive.");
72 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000073 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000074 if (C.capturesVariable() || C.capturesVariableByCopy()) {
75 auto *VD = C.getCapturedVar();
76 assert(VD == VD->getCanonicalDecl() &&
77 "Canonical decl must be captured.");
78 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000079 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000080 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
81 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000082 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000083 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanakaf139ae32019-12-03 15:17:01 -080084 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +000085 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000086 }
87 }
Alexey Bataev475a7442018-01-12 19:39:11 +000088 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000089 }
90};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000091
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000092/// Lexical scope for OpenMP parallel construct, that handles correct codegen
93/// for captured expressions.
94class OMPParallelScope final : public OMPLexicalScope {
95 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
96 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000097 return !(isOpenMPTargetExecutionDirective(Kind) ||
98 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000099 isOpenMPParallelDirective(Kind);
100 }
101
102public:
103 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000104 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
105 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000106};
107
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000108/// Lexical scope for OpenMP teams construct, that handles correct codegen
109/// for captured expressions.
110class OMPTeamsScope final : public OMPLexicalScope {
111 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
112 OpenMPDirectiveKind Kind = S.getDirectiveKind();
113 return !isOpenMPTargetExecutionDirective(Kind) &&
114 isOpenMPTeamsDirective(Kind);
115 }
116
117public:
118 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000119 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
120 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000121};
122
Alexey Bataev5a3af132016-03-29 08:58:54 +0000123/// Private scope for OpenMP loop-based directives, that supports capturing
124/// of used expression from loop statement.
125class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
126 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000127 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevf71939c2019-09-18 19:24:07 +0000128 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000129 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000130 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf71939c2019-09-18 19:24:07 +0000131 EmittedAsPrivate.insert(VD->getCanonicalDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000132 (void)PreCondVars.setVarAddr(
133 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000134 }
Alexey Bataevf71939c2019-09-18 19:24:07 +0000135 // Mark private vars as undefs.
136 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
137 for (const Expr *IRef : C->varlists()) {
138 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
139 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
140 (void)PreCondVars.setVarAddr(
141 CGF, OrigVD,
142 Address(llvm::UndefValue::get(
143 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
144 OrigVD->getType().getNonReferenceType()))),
145 CGF.getContext().getDeclAlign(OrigVD)));
146 }
147 }
148 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000149 (void)PreCondVars.apply(CGF);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000150 // Emit init, __range and __end variables for C++ range loops.
151 const Stmt *Body =
152 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
153 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
Alexey Bataev8bbf2e32019-11-04 09:59:11 -0500154 Body = OMPLoopDirective::tryToFindNextInnerLoop(
155 Body, /*TryImperfectlyNestedLoops=*/true);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000156 if (auto *For = dyn_cast<ForStmt>(Body)) {
157 Body = For->getBody();
158 } else {
159 assert(isa<CXXForRangeStmt>(Body) &&
Alexey Bataevd457f7e2019-10-07 19:57:40 +0000160 "Expected canonical for loop or range-based for loop.");
Alexey Bataevbef93a92019-10-07 18:54:57 +0000161 auto *CXXFor = cast<CXXForRangeStmt>(Body);
162 if (const Stmt *Init = CXXFor->getInit())
163 CGF.EmitStmt(Init);
164 CGF.EmitStmt(CXXFor->getRangeStmt());
165 CGF.EmitStmt(CXXFor->getEndStmt());
166 Body = CXXFor->getBody();
167 }
168 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000169 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000170 for (const auto *I : PreInits->decls())
171 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000172 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000173 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000174 }
175
176public:
177 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
178 : CodeGenFunction::RunCleanupsScope(CGF) {
179 emitPreInitStmt(CGF, S);
180 }
181};
182
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000183class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
184 CodeGenFunction::OMPPrivateScope InlinedShareds;
185
186 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
187 return CGF.LambdaCaptureFields.lookup(VD) ||
188 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
189 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
190 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
191 }
192
193public:
194 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
195 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
196 InlinedShareds(CGF) {
197 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000198 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
199 if (const auto *PreInit =
200 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000201 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000202 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000203 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000204 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000205 CodeGenFunction::AutoVarEmission Emission =
206 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
207 CGF.EmitAutoVarCleanups(Emission);
208 }
209 }
210 }
211 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
212 for (const Expr *E : UDP->varlists()) {
213 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
214 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
215 CGF.EmitVarDecl(*OED);
216 }
217 }
218 }
219 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
220 CGF.EmitOMPPrivateClause(S, InlinedShareds);
221 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
222 if (const Expr *E = TG->getReductionRef())
223 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
224 }
225 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
226 while (CS) {
227 for (auto &C : CS->captures()) {
228 if (C.capturesVariable() || C.capturesVariableByCopy()) {
229 auto *VD = C.getCapturedVar();
230 assert(VD == VD->getCanonicalDecl() &&
231 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000232 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000233 isCapturedVar(CGF, VD) ||
234 (CGF.CapturedStmtInfo &&
235 InlinedShareds.isGlobalVarCaptured(VD)),
236 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000237 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000238 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800239 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000240 });
241 }
242 }
243 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
244 }
245 (void)InlinedShareds.Privatize();
246 }
247};
248
Alexey Bataev3392d762016-02-16 11:18:12 +0000249} // namespace
250
Alexey Bataevf8365372017-11-17 17:57:25 +0000251static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
252 const OMPExecutableDirective &S,
253 const RegionCodeGenTy &CodeGen);
254
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000255LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000256 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
257 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000258 OrigVD = OrigVD->getCanonicalDecl();
259 bool IsCaptured =
260 LambdaCaptureFields.lookup(OrigVD) ||
261 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
262 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000263 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000264 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
265 return EmitLValue(&DRE);
266 }
267 }
268 return EmitLValue(E);
269}
270
Alexey Bataev1189bd02016-01-26 12:20:39 +0000271llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000272 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000273 llvm::Value *Size = nullptr;
274 auto SizeInChars = C.getTypeSizeInChars(Ty);
275 if (SizeInChars.isZero()) {
276 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000277 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
278 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000279 Ty = VlaSize.Type;
280 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
281 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000282 }
283 SizeInChars = C.getTypeSizeInChars(Ty);
284 if (SizeInChars.isZero())
285 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000286 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
287 }
288 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000289}
290
Alexey Bataev2377fe92015-09-10 08:12:02 +0000291void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000292 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000293 const RecordDecl *RD = S.getCapturedRecordDecl();
294 auto CurField = RD->field_begin();
295 auto CurCap = S.captures().begin();
296 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
297 E = S.capture_init_end();
298 I != E; ++I, ++CurField, ++CurCap) {
299 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000300 const VariableArrayType *VAT = CurField->getCapturedVLAType();
301 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000302 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000303 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000304 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000305 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000306 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000307
308 // If the field is not a pointer, we need to save the actual value
309 // and load it as a void pointer.
310 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000311 ASTContext &Ctx = getContext();
312 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000313 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000314 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000315 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
316
Alexey Bataevddf3db92018-04-13 17:31:06 +0000317 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000318 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000319 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000320 LValue SrcLV =
321 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
322
323 // Store the value using the source type pointer.
324 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
325
326 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000327 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000328 }
329 CapturedVars.push_back(CV);
330 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000331 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800332 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000333 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000334 }
335}
336
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000337static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
338 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000339 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000340 ASTContext &Ctx = CGF.getContext();
341
Alexey Bataevddf3db92018-04-13 17:31:06 +0000342 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800343 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000344 Ctx.getPointerType(DstType), Loc);
345 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000346 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800347 .getAddress(CGF);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000348 return TmpAddr;
349}
350
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000351static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000352 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000353 return C.getLValueReferenceType(
354 getCanonicalParamType(C, T.getNonReferenceType()),
355 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000356 if (T->isPointerType())
357 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000358 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
359 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000360 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000361 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000362 return C.getCanonicalType(T);
363 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000364 return C.getCanonicalParamType(T);
365}
366
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000367namespace {
368 /// Contains required data for proper outlined function codegen.
369 struct FunctionOptions {
370 /// Captured statement for which the function is generated.
371 const CapturedStmt *S = nullptr;
372 /// true if cast to/from UIntPtr is required for variables captured by
373 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000374 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000375 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000377 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000378 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000379 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000380 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
381 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000382 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000383 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
384 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000385 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 };
387}
388
Alexey Bataeve754b182017-08-09 19:38:53 +0000389static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000390 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000391 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000392 &LocalAddrs,
393 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
394 &VLASizes,
395 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
396 const CapturedDecl *CD = FO.S->getCapturedDecl();
397 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000398 assert(CD->hasBody() && "missing CapturedDecl body");
399
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000400 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000401 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000402 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000403 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000404 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000405 Args.append(CD->param_begin(),
406 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000407 TargetArgs.append(
408 CD->param_begin(),
409 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000410 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000411 FunctionDecl *DebugFunctionDecl = nullptr;
412 if (!FO.UIntPtrCastRequired) {
413 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000414 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000415 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000416 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000417 SourceLocation(), DeclarationName(), FunctionTy,
418 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
419 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000420 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000421 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000422 QualType ArgType = FD->getType();
423 IdentifierInfo *II = nullptr;
424 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000425
426 // If this is a capture by copy and the type is not a pointer, the outlined
427 // function argument type should be uintptr and the value properly casted to
428 // uintptr. This is necessary given that the runtime library is only able to
429 // deal with pointers. We can pass in the same way the VLA type sizes to the
430 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000431 if (FO.UIntPtrCastRequired &&
432 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
433 I->capturesVariableArrayType()))
434 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000435
436 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000437 CapVar = I->getCapturedVar();
438 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000439 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000440 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000441 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000442 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000443 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000444 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000445 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000446 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000447 VarDecl *Arg;
448 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
449 Arg = ParmVarDecl::Create(
450 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000451 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000452 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
453 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
454 } else {
455 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
456 II, ArgType, ImplicitParamDecl::Other);
457 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000458 Args.emplace_back(Arg);
459 // Do not cast arguments if we emit function with non-original types.
460 TargetArgs.emplace_back(
461 FO.UIntPtrCastRequired
462 ? Arg
463 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000464 ++I;
465 }
466 Args.append(
467 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
468 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000469 TargetArgs.append(
470 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
471 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000472
473 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000474 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000475 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000476 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
477
Alexey Bataevddf3db92018-04-13 17:31:06 +0000478 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000479 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
480 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000481 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
482 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000483 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000484 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000485
486 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000487 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000488 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000489 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000490 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000491 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000492 // Do not map arguments if we emit function with non-original types.
493 Address LocalAddr(Address::invalid());
494 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
495 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
496 TargetArgs[Cnt]);
497 } else {
498 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
499 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000500 // If we are capturing a pointer by copy we don't need to do anything, just
501 // use the value that we get from the arguments.
502 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000503 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 if (!FO.RegisterCastedArgsOnly)
505 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000506 ++Cnt;
507 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000508 continue;
509 }
510
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000511 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
512 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000513 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000514 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000515 ArgLVal = CGF.MakeAddrLValue(
516 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
517 Args[Cnt]->getName(), ArgLVal),
518 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000519 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000520 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
521 const VariableArrayType *VAT = FD->getCapturedVLAType();
522 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000523 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000524 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000525 QualType VarTy = Var->getType();
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800526 Address ArgAddr = ArgLVal.getAddress(CGF);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000527 if (ArgLVal.getType()->isLValueReferenceType()) {
528 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
529 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
530 assert(ArgLVal.getType()->isPointerType());
531 ArgAddr = CGF.EmitLoadOfPointer(
532 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000533 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000534 if (!FO.RegisterCastedArgsOnly) {
535 LocalAddrs.insert(
536 {Args[Cnt],
537 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
538 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000539 } else if (I->capturesVariableByCopy()) {
540 assert(!FD->getType()->isAnyPointerType() &&
541 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000542 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000543 LocalAddrs.insert({Args[Cnt],
544 {Var, FO.UIntPtrCastRequired
545 ? castValueFromUintptr(
546 CGF, I->getLocation(), FD->getType(),
547 Args[Cnt]->getName(), ArgLVal)
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800548 : ArgLVal.getAddress(CGF)}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000549 } else {
550 // If 'this' is captured, load it into CXXThisValue.
551 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000552 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800553 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000554 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000555 ++Cnt;
556 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000557 }
558
Alexey Bataeve754b182017-08-09 19:38:53 +0000559 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000560}
561
562llvm::Function *
563CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
564 assert(
565 CapturedStmtInfo &&
566 "CapturedStmtInfo should be set when generating the captured function");
567 const CapturedDecl *CD = S.getCapturedDecl();
568 // Build the argument list.
569 bool NeedWrapperFunction =
570 getDebugInfo() &&
571 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
572 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000573 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000574 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000575 SmallString<256> Buffer;
576 llvm::raw_svector_ostream Out(Buffer);
577 Out << CapturedStmtInfo->getHelperName();
578 if (NeedWrapperFunction)
579 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000580 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000581 Out.str());
582 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
583 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000584 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000585 for (const auto &LocalAddrPair : LocalAddrs) {
586 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000587 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
588 return LocalAddrPair.second.second;
589 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 }
591 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000592 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000593 for (const auto &VLASizePair : VLASizes)
594 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000595 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000596 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000597 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000598 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000599 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000600 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000601
Alexey Bataevefd884d2017-08-04 21:26:25 +0000602 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000603 /*RegisterCastedArgsOnly=*/true,
604 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000605 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000606 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000607 Args.clear();
608 LocalAddrs.clear();
609 VLASizes.clear();
610 llvm::Function *WrapperF =
611 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000612 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000613 llvm::SmallVector<llvm::Value *, 4> CallArgs;
614 for (const auto *Arg : Args) {
615 llvm::Value *CallArg;
616 auto I = LocalAddrs.find(Arg);
617 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000618 LValue LV = WrapperCGF.MakeAddrLValue(
619 I->second.second,
620 I->second.first ? I->second.first->getType() : Arg->getType(),
621 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000622 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000623 } else {
624 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000625 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000626 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000627 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000628 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000629 Arg->getType(),
630 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000631 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000632 }
633 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000634 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000635 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000636 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000637 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000638 WrapperCGF.FinishFunction();
639 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000640}
641
Alexey Bataev9959db52014-05-06 10:08:46 +0000642//===----------------------------------------------------------------------===//
643// OpenMP Directive Emission
644//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000645void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000646 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000647 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000648 // Perform element-by-element initialization.
649 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000650
651 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000652 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
653 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000654 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
655
Alexey Bataevddf3db92018-04-13 17:31:06 +0000656 llvm::Value *SrcBegin = SrcAddr.getPointer();
657 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000658 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000659 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000660 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000661 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
662 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
663 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000664 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
665 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000666
Alexey Bataev420d45b2015-04-14 05:11:24 +0000667 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000668 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000669 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000670
671 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
672
673 llvm::PHINode *SrcElementPHI =
674 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
675 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
676 Address SrcElementCurrent =
677 Address(SrcElementPHI,
678 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
679
680 llvm::PHINode *DestElementPHI =
681 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
682 DestElementPHI->addIncoming(DestBegin, EntryBB);
683 Address DestElementCurrent =
684 Address(DestElementPHI,
685 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000686
Alexey Bataev420d45b2015-04-14 05:11:24 +0000687 // Emit copy.
688 CopyGen(DestElementCurrent, SrcElementCurrent);
689
690 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000691 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000692 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000693 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000694 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000695 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000696 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000697 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
698 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000699 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
700 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000701
702 // Done.
703 EmitBlock(DoneBB, /*IsFinished=*/true);
704}
705
John McCall7f416cc2015-09-08 08:05:57 +0000706void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
707 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000708 const VarDecl *SrcVD, const Expr *Copy) {
709 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000710 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000711 if (BO && BO->getOpcode() == BO_Assign) {
712 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000713 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
714 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
715 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 } else {
717 // For arrays with complex element types perform element by element
718 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000719 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000720 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000721 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 // Working with the single array element, so have to remap
723 // destination and source variables to corresponding array
724 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000725 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000726 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
727 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000728 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000729 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000730 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000731 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000732 } else {
733 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000734 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000735 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
736 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000737 (void)Remap.Privatize();
738 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000739 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000740 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000741}
742
Alexey Bataev69c62a92015-04-15 04:52:20 +0000743bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
744 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000745 if (!HaveInsertPoint())
746 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000747 bool DeviceConstTarget =
748 getLangOpts().OpenMPIsDevice &&
749 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000750 bool FirstprivateIsLastprivate = false;
751 llvm::DenseSet<const VarDecl *> Lastprivates;
752 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
753 for (const auto *D : C->varlists())
754 Lastprivates.insert(
755 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
756 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000757 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000758 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
759 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
760 // Force emission of the firstprivate copy if the directive does not emit
761 // outlined function, like omp for, omp simd, omp distribute etc.
762 bool MustEmitFirstprivateCopy =
763 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000764 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000765 auto IRef = C->varlist_begin();
766 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000767 for (const Expr *IInit : C->private_copies()) {
768 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000769 bool ThisFirstprivateIsLastprivate =
770 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000771 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000772 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000773 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000774 !FD->getType()->isReferenceType() &&
775 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000776 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
777 ++IRef;
778 ++InitsRef;
779 continue;
780 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000781 // Do not emit copy for firstprivate constant variables in target regions,
782 // captured by reference.
783 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000784 FD && FD->getType()->isReferenceType() &&
785 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000786 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
787 OrigVD);
788 ++IRef;
789 ++InitsRef;
790 continue;
791 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000792 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000794 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000795 const auto *VDInit =
796 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000797 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000798 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
800 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataeve0ef04f2019-05-23 22:30:43 +0000801 LValue OriginalLVal;
802 if (!FD) {
803 // Check if the firstprivate variable is just a constant value.
804 ConstantEmission CE = tryEmitAsConstant(&DRE);
805 if (CE && !CE.isReference()) {
806 // Constant value, no need to create a copy.
807 ++IRef;
808 ++InitsRef;
809 continue;
810 }
811 if (CE && CE.isReference()) {
812 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
813 } else {
814 assert(!CE && "Expected non-constant firstprivate.");
815 OriginalLVal = EmitLValue(&DRE);
816 }
817 } else {
818 OriginalLVal = EmitLValue(&DRE);
819 }
Alexey Bataevfeddd642016-04-22 09:05:03 +0000820 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000821 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000822 // Emit VarDecl with copy init for arrays.
823 // Get the address of the original variable captured in current
824 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000825 IsRegistered = PrivateScope.addPrivate(
826 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
827 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
828 const Expr *Init = VD->getInit();
829 if (!isa<CXXConstructExpr>(Init) ||
830 isTrivialInitializer(Init)) {
831 // Perform simple memcpy.
832 LValue Dest =
833 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
834 EmitAggregateAssign(Dest, OriginalLVal, Type);
835 } else {
836 EmitOMPAggregateAssign(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800837 Emission.getAllocatedAddress(),
838 OriginalLVal.getAddress(*this), Type,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000839 [this, VDInit, Init](Address DestElement,
840 Address SrcElement) {
841 // Clean up any temporaries needed by the
842 // initialization.
843 RunCleanupsScope InitScope(*this);
844 // Emit initialization for single element.
845 setAddrOfLocalVar(VDInit, SrcElement);
846 EmitAnyExprToMem(Init, DestElement,
847 Init->getType().getQualifiers(),
848 /*IsInitializer*/ false);
849 LocalDeclMap.erase(VDInit);
850 });
851 }
852 EmitAutoVarCleanups(Emission);
853 return Emission.getAllocatedAddress();
854 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000855 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800856 Address OriginalAddr = OriginalLVal.getAddress(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000857 IsRegistered = PrivateScope.addPrivate(
858 OrigVD, [this, VDInit, OriginalAddr, VD]() {
859 // Emit private VarDecl with copy init.
860 // Remap temp VDInit variable to the address of the original
861 // variable (for proper handling of captured global variables).
862 setAddrOfLocalVar(VDInit, OriginalAddr);
863 EmitDecl(*VD);
864 LocalDeclMap.erase(VDInit);
865 return GetAddrOfLocalVar(VD);
866 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000867 }
868 assert(IsRegistered &&
869 "firstprivate var already registered as private");
870 // Silence the warning about unused variable.
871 (void)IsRegistered;
872 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000873 ++IRef;
874 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000875 }
876 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000877 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000878}
879
Alexey Bataev03b340a2014-10-21 03:16:40 +0000880void CodeGenFunction::EmitOMPPrivateClause(
881 const OMPExecutableDirective &D,
882 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000883 if (!HaveInsertPoint())
884 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000885 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000886 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000887 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000888 for (const Expr *IInit : C->private_copies()) {
889 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000890 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000891 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
892 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
893 // Emit private VarDecl with copy init.
894 EmitDecl(*VD);
895 return GetAddrOfLocalVar(VD);
896 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000897 assert(IsRegistered && "private var already registered as private");
898 // Silence the warning about unused variable.
899 (void)IsRegistered;
900 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000901 ++IRef;
902 }
903 }
904}
905
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000906bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000907 if (!HaveInsertPoint())
908 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000909 // threadprivate_var1 = master_threadprivate_var1;
910 // operator=(threadprivate_var2, master_threadprivate_var2);
911 // ...
912 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000913 llvm::DenseSet<const VarDecl *> CopiedVars;
914 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000915 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000916 auto IRef = C->varlist_begin();
917 auto ISrcRef = C->source_exprs().begin();
918 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000919 for (const Expr *AssignOp : C->assignment_ops()) {
920 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000921 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000922 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000923 // Get the address of the master variable. If we are emitting code with
924 // TLS support, the address is passed from the master as field in the
925 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000926 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000927 if (getLangOpts().OpenMPUseTLS &&
928 getContext().getTargetInfo().isTLSSupported()) {
929 assert(CapturedStmtInfo->lookup(VD) &&
930 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000931 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
932 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800933 MasterAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000934 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000935 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000936 MasterAddr =
937 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
938 : CGM.GetAddrOfGlobal(VD),
939 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000940 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000941 // Get the address of the threadprivate variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800942 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000943 if (CopiedVars.size() == 1) {
944 // At first check if current thread is a master thread. If it is, no
945 // need to copy data.
946 CopyBegin = createBasicBlock("copyin.not.master");
947 CopyEnd = createBasicBlock("copyin.not.master.end");
948 Builder.CreateCondBr(
949 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000950 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000951 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
952 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000953 CopyBegin, CopyEnd);
954 EmitBlock(CopyBegin);
955 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000956 const auto *SrcVD =
957 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
958 const auto *DestVD =
959 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000960 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000961 }
962 ++IRef;
963 ++ISrcRef;
964 ++IDestRef;
965 }
966 }
967 if (CopyEnd) {
968 // Exit out of copying procedure for non-master thread.
969 EmitBlock(CopyEnd, /*IsFinished=*/true);
970 return true;
971 }
972 return false;
973}
974
Alexey Bataev38e89532015-04-16 04:54:05 +0000975bool CodeGenFunction::EmitOMPLastprivateClauseInit(
976 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000977 if (!HaveInsertPoint())
978 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000979 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000980 llvm::DenseSet<const VarDecl *> SIMDLCVs;
981 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000982 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
983 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000984 SIMDLCVs.insert(
985 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
986 }
987 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000988 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000989 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000990 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000991 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
992 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000993 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000994 auto IRef = C->varlist_begin();
995 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000996 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000997 // Keep the address of the original variable for future update at the end
998 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000999 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00001000 // Taskloops do not require additional initialization, it is done in
1001 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +00001002 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001003 const auto *DestVD =
1004 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1005 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001006 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1007 /*RefersToEnclosingVariableOrCapture=*/
1008 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1009 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001010 return EmitLValue(&DRE).getAddress(*this);
Alexey Bataev38e89532015-04-16 04:54:05 +00001011 });
1012 // Check if the variable is also a firstprivate: in this case IInit is
1013 // not generated. Initialization of this variable will happen in codegen
1014 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001015 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001016 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1017 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +00001018 // Emit private VarDecl with copy init.
1019 EmitDecl(*VD);
1020 return GetAddrOfLocalVar(VD);
1021 });
Alexey Bataevd130fd12015-05-13 10:23:02 +00001022 assert(IsRegistered &&
1023 "lastprivate var already registered as private");
1024 (void)IsRegistered;
1025 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001026 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001027 ++IRef;
1028 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001029 }
1030 }
1031 return HasAtLeastOneLastprivate;
1032}
1033
1034void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001035 const OMPExecutableDirective &D, bool NoFinals,
1036 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001037 if (!HaveInsertPoint())
1038 return;
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 // Emit following code:
1040 // if (<IsLastIterCond>) {
1041 // orig_var1 = private_orig_var1;
1042 // ...
1043 // orig_varn = private_orig_varn;
1044 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001045 llvm::BasicBlock *ThenBB = nullptr;
1046 llvm::BasicBlock *DoneBB = nullptr;
1047 if (IsLastIterCond) {
Alexey Bataeva58da1a2019-12-27 09:44:43 -05001048 // Emit implicit barrier if at least one lastprivate conditional is found
1049 // and this is not a simd mode.
1050 if (!getLangOpts().OpenMPSimd &&
1051 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1052 [](const OMPLastprivateClause *C) {
1053 return C->getKind() == OMPC_LASTPRIVATE_conditional;
1054 })) {
1055 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1056 OMPD_unknown,
1057 /*EmitChecks=*/false,
1058 /*ForceSimpleCall=*/true);
1059 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001060 ThenBB = createBasicBlock(".omp.lastprivate.then");
1061 DoneBB = createBasicBlock(".omp.lastprivate.done");
1062 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1063 EmitBlock(ThenBB);
1064 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001065 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1066 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001067 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001068 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001069 for (const Expr *F : LoopDirective->finals()) {
1070 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001071 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1072 if (NoFinals)
1073 AlreadyEmittedVars.insert(D);
1074 else
1075 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001076 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001077 }
1078 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001079 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1080 auto IRef = C->varlist_begin();
1081 auto ISrcRef = C->source_exprs().begin();
1082 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001083 for (const Expr *AssignOp : C->assignment_ops()) {
1084 const auto *PrivateVD =
1085 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001086 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001087 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001088 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1089 // If lastprivate variable is a loop control variable for loop-based
1090 // directive, update its value before copyin back to original
1091 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001092 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001093 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001094 const auto *SrcVD =
1095 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1096 const auto *DestVD =
1097 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001098 // Get the address of the private variable.
1099 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001100 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001101 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001102 Address(Builder.CreateLoad(PrivateAddr),
1103 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataeva58da1a2019-12-27 09:44:43 -05001104 // Store the last value to the private copy in the last iteration.
1105 if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1106 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1107 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1108 (*IRef)->getExprLoc());
1109 // Get the address of the original variable.
1110 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001111 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001112 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001113 ++IRef;
1114 ++ISrcRef;
1115 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001116 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001117 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001118 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001119 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001120 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001121 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001122}
1123
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001124void CodeGenFunction::EmitOMPReductionClauseInit(
1125 const OMPExecutableDirective &D,
1126 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001127 if (!HaveInsertPoint())
1128 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 SmallVector<const Expr *, 4> Shareds;
1130 SmallVector<const Expr *, 4> Privates;
1131 SmallVector<const Expr *, 4> ReductionOps;
1132 SmallVector<const Expr *, 4> LHSs;
1133 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001134 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001135 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001136 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001137 auto ILHS = C->lhs_exprs().begin();
1138 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001139 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001140 Shareds.emplace_back(Ref);
1141 Privates.emplace_back(*IPriv);
1142 ReductionOps.emplace_back(*IRed);
1143 LHSs.emplace_back(*ILHS);
1144 RHSs.emplace_back(*IRHS);
1145 std::advance(IPriv, 1);
1146 std::advance(IRed, 1);
1147 std::advance(ILHS, 1);
1148 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001149 }
1150 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001151 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1152 unsigned Count = 0;
1153 auto ILHS = LHSs.begin();
1154 auto IRHS = RHSs.begin();
1155 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001156 for (const Expr *IRef : Shareds) {
1157 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001158 // Emit private VarDecl with reduction init.
1159 RedCG.emitSharedLValue(*this, Count);
1160 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001161 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001162 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1163 RedCG.getSharedLValue(Count),
1164 [&Emission](CodeGenFunction &CGF) {
1165 CGF.EmitAutoVarInit(Emission);
1166 return true;
1167 });
1168 EmitAutoVarCleanups(Emission);
1169 Address BaseAddr = RedCG.adjustPrivateAddress(
1170 *this, Count, Emission.getAllocatedAddress());
1171 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001172 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001173 assert(IsRegistered && "private var already registered as private");
1174 // Silence the warning about unused variable.
1175 (void)IsRegistered;
1176
Alexey Bataevddf3db92018-04-13 17:31:06 +00001177 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1178 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001179 QualType Type = PrivateVD->getType();
1180 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1181 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001182 // Store the address of the original variable associated with the LHS
1183 // implicit variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001184 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1185 return RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001186 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001187 PrivateScope.addPrivate(
1188 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001189 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1190 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001191 // Store the address of the original variable associated with the LHS
1192 // implicit variable.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001193 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1194 return RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001195 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001196 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001197 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1198 ConvertTypeForMem(RHSVD->getType()),
1199 "rhs.begin");
1200 });
1201 } else {
1202 QualType Type = PrivateVD->getType();
1203 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001204 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001205 // Store the address of the original variable associated with the LHS
1206 // implicit variable.
1207 if (IsArray) {
1208 OriginalAddr = Builder.CreateElementBitCast(
1209 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1210 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001211 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001212 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001213 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001214 return IsArray
1215 ? Builder.CreateElementBitCast(
1216 GetAddrOfLocalVar(PrivateVD),
1217 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1218 : GetAddrOfLocalVar(PrivateVD);
1219 });
1220 }
1221 ++ILHS;
1222 ++IRHS;
1223 ++IPriv;
1224 ++Count;
1225 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001226}
1227
1228void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001229 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001230 if (!HaveInsertPoint())
1231 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001232 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001233 llvm::SmallVector<const Expr *, 8> LHSExprs;
1234 llvm::SmallVector<const Expr *, 8> RHSExprs;
1235 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001236 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001237 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001238 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001239 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001240 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1241 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1242 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1243 }
1244 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001245 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1246 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001247 ReductionKind == OMPD_simd;
1248 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001249 // Emit nowait reduction if nowait clause is present or directive is a
1250 // parallel directive (it always has implicit barrier).
1251 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001252 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001253 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001254 }
1255}
1256
Alexey Bataev61205072016-03-02 04:57:40 +00001257static void emitPostUpdateForReductionClause(
1258 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001259 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001260 if (!CGF.HaveInsertPoint())
1261 return;
1262 llvm::BasicBlock *DoneBB = nullptr;
1263 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001264 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001265 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001266 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001267 // If the first post-update expression is found, emit conditional
1268 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001269 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001270 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1271 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1272 CGF.EmitBlock(ThenBB);
1273 }
1274 }
1275 CGF.EmitIgnoredExpr(PostUpdate);
1276 }
1277 }
1278 if (DoneBB)
1279 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1280}
1281
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001282namespace {
1283/// Codegen lambda for appending distribute lower and upper bounds to outlined
1284/// parallel function. This is necessary for combined constructs such as
1285/// 'distribute parallel for'
1286typedef llvm::function_ref<void(CodeGenFunction &,
1287 const OMPExecutableDirective &,
1288 llvm::SmallVectorImpl<llvm::Value *> &)>
1289 CodeGenBoundParametersTy;
1290} // anonymous namespace
1291
1292static void emitCommonOMPParallelDirective(
1293 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1294 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1295 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001296 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001297 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001298 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1299 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001300 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001301 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001302 llvm::Value *NumThreads =
1303 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1304 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001305 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001306 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001307 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001308 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001309 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001310 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001311 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001312 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001313 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001314 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1315 if (C->getNameModifier() == OMPD_unknown ||
1316 C->getNameModifier() == OMPD_parallel) {
1317 IfCond = C->getCondition();
1318 break;
1319 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001320 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001321
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001322 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001323 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001324 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1325 // lower and upper bounds with the pragma 'for' chunking mechanism.
1326 // The following lambda takes care of appending the lower and upper bound
1327 // parameters when necessary
1328 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001329 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001330 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001331 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001332}
1333
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001334static void emitEmptyBoundParameters(CodeGenFunction &,
1335 const OMPExecutableDirective &,
1336 llvm::SmallVectorImpl<llvm::Value *> &) {}
1337
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001338void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Johannes Doerfert10fedd92019-12-26 11:23:38 -06001339
1340 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
1341 // Check if we have any if clause associated with the directive.
1342 llvm::Value *IfCond = nullptr;
1343 if (const auto *C = S.getSingleClause<OMPIfClause>())
1344 IfCond = EmitScalarExpr(C->getCondition(),
1345 /*IgnoreResultAssign=*/true);
1346
1347 llvm::Value *NumThreads = nullptr;
1348 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1349 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1350 /*IgnoreResultAssign=*/true);
1351
1352 ProcBindKind ProcBind = OMP_PROC_BIND_default;
1353 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1354 ProcBind = ProcBindClause->getProcBindKind();
1355
1356 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1357
1358 // The cleanup callback that finalizes all variabels at the given location,
1359 // thus calls destructors etc.
1360 auto FiniCB = [this](InsertPointTy IP) {
1361 CGBuilderTy::InsertPointGuard IPG(Builder);
1362 assert(IP.getBlock()->end() != IP.getPoint() &&
1363 "OpenMP IR Builder should cause terminated block!");
1364 llvm::BasicBlock *IPBB = IP.getBlock();
1365 llvm::BasicBlock *DestBB = IPBB->splitBasicBlock(IP.getPoint());
1366 IPBB->getTerminator()->eraseFromParent();
1367 Builder.SetInsertPoint(IPBB);
1368 CodeGenFunction::JumpDest Dest = getJumpDestInCurrentScope(DestBB);
1369 EmitBranchThroughCleanup(Dest);
1370 };
1371
1372 // Privatization callback that performs appropriate action for
1373 // shared/private/firstprivate/lastprivate/copyin/... variables.
1374 //
1375 // TODO: This defaults to shared right now.
1376 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1377 llvm::Value &Val, llvm::Value *&ReplVal) {
1378 // The next line is appropriate only for variables (Val) with the
1379 // data-sharing attribute "shared".
1380 ReplVal = &Val;
1381
1382 return CodeGenIP;
1383 };
1384
1385 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1386 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1387
1388 auto BodyGenCB = [ParallelRegionBodyStmt,
1389 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1390 llvm::BasicBlock &ContinuationBB) {
1391 auto OldAllocaIP = AllocaInsertPt;
1392 AllocaInsertPt = &*AllocaIP.getPoint();
1393
1394 auto OldReturnBlock = ReturnBlock;
1395 ReturnBlock = getJumpDestInCurrentScope(&ContinuationBB);
1396
1397 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1398 CodeGenIPBB->splitBasicBlock(CodeGenIP.getPoint());
1399 llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator();
1400 CodeGenIPBBTI->removeFromParent();
1401
1402 Builder.SetInsertPoint(CodeGenIPBB);
1403
1404 EmitStmt(ParallelRegionBodyStmt);
1405
1406 Builder.Insert(CodeGenIPBBTI);
1407
1408 AllocaInsertPt = OldAllocaIP;
1409 ReturnBlock = OldReturnBlock;
1410 };
1411
1412 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1413 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1414 Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB,
1415 FiniCB, IfCond, NumThreads,
1416 ProcBind, S.hasCancel()));
1417 return;
1418 }
1419
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001420 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001421 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001422 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001423 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001424 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001425 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1426 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001427 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001428 // propagation master's thread values of threadprivate variables to local
1429 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001430 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001431 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001432 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001433 }
1434 CGF.EmitOMPPrivateClause(S, PrivateScope);
1435 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1436 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001437 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001438 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001439 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001440 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1441 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001442 emitPostUpdateForReductionClause(*this, S,
1443 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001444}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001445
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001446static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1447 int MaxLevel, int Level = 0) {
1448 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1449 const Stmt *SimplifiedS = S->IgnoreContainers();
1450 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1451 PrettyStackTraceLoc CrashInfo(
1452 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1453 "LLVM IR generation of compound statement ('{}')");
1454
1455 // Keep track of the current cleanup stack depth, including debug scopes.
1456 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1457 for (const Stmt *CurStmt : CS->body())
1458 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1459 return;
1460 }
1461 if (SimplifiedS == NextLoop) {
1462 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1463 S = For->getBody();
1464 } else {
1465 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1466 "Expected canonical for loop or range-based for loop.");
1467 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1468 CGF.EmitStmt(CXXFor->getLoopVarStmt());
1469 S = CXXFor->getBody();
1470 }
1471 if (Level + 1 < MaxLevel) {
1472 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1473 S, /*TryImperfectlyNestedLoops=*/true);
1474 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1475 return;
1476 }
1477 }
1478 CGF.EmitStmt(S);
1479}
1480
Alexey Bataev0f34da12015-07-02 04:17:07 +00001481void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1482 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001483 RunCleanupsScope BodyScope(*this);
1484 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001485 for (const Expr *UE : D.updates())
1486 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001487 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001488 // In distribute directives only loop counters may be marked as linear, no
1489 // need to generate the code for them.
1490 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1491 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001492 for (const Expr *UE : C->updates())
1493 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001494 }
Alexander Musman3276a272015-03-21 10:12:56 +00001495 }
1496
Alexander Musmana5f070a2014-10-01 06:03:56 +00001497 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001498 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001499 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexey Bataevf8be4762019-08-14 19:30:06 +00001500 for (const Expr *E : D.finals_conditions()) {
1501 if (!E)
1502 continue;
1503 // Check that loop counter in non-rectangular nest fits into the iteration
1504 // space.
1505 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1506 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1507 getProfileCount(D.getBody()));
1508 EmitBlock(NextBB);
1509 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00001510 // Emit loop variables for C++ range loops.
1511 const Stmt *Body =
1512 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001513 // Emit loop body.
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001514 emitBody(*this, Body,
1515 OMPLoopDirective::tryToFindNextInnerLoop(
1516 Body, /*TryImperfectlyNestedLoops=*/true),
1517 D.getCollapsedNumber());
1518
Alexander Musmana5f070a2014-10-01 06:03:56 +00001519 // The end (updates/cleanups).
1520 EmitBlock(Continue.getBlock());
1521 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001522}
1523
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001524void CodeGenFunction::EmitOMPInnerLoop(
1525 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1526 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001527 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1528 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001529 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001530
1531 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001532 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001533 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001534 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001535 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1536 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001537
1538 // If there are any cleanups between here and the loop-exit scope,
1539 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001540 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001541 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001542 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001543
Alexey Bataevddf3db92018-04-13 17:31:06 +00001544 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001545
Alexey Bataev2df54a02015-03-12 08:53:29 +00001546 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001547 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001548 if (ExitBlock != LoopExit.getBlock()) {
1549 EmitBlock(ExitBlock);
1550 EmitBranchThroughCleanup(LoopExit);
1551 }
1552
1553 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001554 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001555
1556 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001557 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001558 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1559
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001560 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001561
1562 // Emit "IV = IV + 1" and a back-edge to the condition block.
1563 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001564 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001565 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001566 BreakContinueStack.pop_back();
1567 EmitBranch(CondBlock);
1568 LoopStack.pop();
1569 // Emit the fall-through block.
1570 EmitBlock(LoopExit.getBlock());
1571}
1572
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001573bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001574 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001575 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001576 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001577 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001578 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001579 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001580 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001581 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1582 if (const auto *Ref =
1583 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001584 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001585 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001586 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001587 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1588 VD->getInit()->getType(), VK_LValue,
1589 VD->getInit()->getExprLoc());
1590 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1591 VD->getType()),
1592 /*capturedByInit=*/false);
1593 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001594 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001595 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001596 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001597 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001598 // Emit the linear steps for the linear clauses.
1599 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001600 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1601 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001602 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001603 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001604 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001605 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001606 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001607 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001608}
1609
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001610void CodeGenFunction::EmitOMPLinearClauseFinal(
1611 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001612 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001613 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001614 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001615 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001616 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001617 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001618 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001619 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001620 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001621 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001622 // If the first post-update expression is found, emit conditional
1623 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001624 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001625 DoneBB = createBasicBlock(".omp.linear.pu.done");
1626 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1627 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001628 }
1629 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001630 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001631 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001632 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001633 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001634 Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001635 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001636 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001637 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001638 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001639 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001640 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001641 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001642 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001643 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001644 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001645 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001646}
1647
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001648static void emitAlignedClause(CodeGenFunction &CGF,
1649 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001650 if (!CGF.HaveInsertPoint())
1651 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001652 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Erich Keanef7593952019-10-11 14:59:44 +00001653 llvm::APInt ClauseAlignment(64, 0);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001654 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1655 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001656 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
Erich Keanef7593952019-10-11 14:59:44 +00001657 ClauseAlignment = AlignmentCI->getValue();
Alexander Musman09184fe2014-09-30 05:29:28 +00001658 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001659 for (const Expr *E : Clause->varlists()) {
Erich Keanef7593952019-10-11 14:59:44 +00001660 llvm::APInt Alignment(ClauseAlignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001661 if (Alignment == 0) {
1662 // OpenMP [2.8.1, Description]
1663 // If no optional parameter is specified, implementation-defined default
1664 // alignments for SIMD instructions on the target platforms are assumed.
1665 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001666 CGF.getContext()
1667 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1668 E->getType()->getPointeeType()))
1669 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001670 }
Erich Keanef7593952019-10-11 14:59:44 +00001671 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001672 "alignment is not power of 2");
1673 if (Alignment != 0) {
1674 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001675 CGF.EmitAlignmentAssumption(
Erich Keanef7593952019-10-11 14:59:44 +00001676 PtrValue, E, /*No second loc needed*/ SourceLocation(),
1677 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001678 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001679 }
1680 }
1681}
1682
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001683void CodeGenFunction::EmitOMPPrivateLoopCounters(
1684 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1685 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001686 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001687 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001688 for (const Expr *E : S.counters()) {
1689 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1690 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001691 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001692 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001693 EmitAutoVarCleanups(VarEmission);
1694 LocalDeclMap.erase(PrivateVD);
1695 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1696 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001697 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001698 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1699 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001700 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001701 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001702 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1703 E->getType(), VK_LValue, E->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001704 return EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001705 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001706 } else {
1707 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1708 return VarEmission.getAllocatedAddress();
1709 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001710 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001711 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001712 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001713 // Privatize extra loop counters used in loops for ordered(n) clauses.
1714 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1715 if (!C->getNumForLoops())
1716 continue;
1717 for (unsigned I = S.getCollapsedNumber(),
1718 E = C->getLoopNumIterations().size();
1719 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001720 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001721 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001722 // Override only those variables that can be captured to avoid re-emission
1723 // of the variables declared within the loops.
1724 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001725 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1726 return CreateMemTemp(DRE->getType(), VD->getName());
1727 });
1728 }
1729 }
1730 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001731}
1732
Alexey Bataev62dbb972015-04-22 11:59:37 +00001733static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1734 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1735 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001736 if (!CGF.HaveInsertPoint())
1737 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001738 {
1739 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001740 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001741 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001742 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001743 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001744 CGF.EmitIgnoredExpr(I);
1745 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001746 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00001747 // Create temp loop control variables with their init values to support
1748 // non-rectangular loops.
1749 CodeGenFunction::OMPMapVars PreCondVars;
1750 for (const Expr * E: S.dependent_counters()) {
1751 if (!E)
1752 continue;
1753 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1754 "dependent counter must not be an iterator.");
1755 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1756 Address CounterAddr =
1757 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1758 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1759 }
1760 (void)PreCondVars.apply(CGF);
1761 for (const Expr *E : S.dependent_inits()) {
1762 if (!E)
1763 continue;
1764 CGF.EmitIgnoredExpr(E);
1765 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001766 // Check that loop is executed at least one time.
1767 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00001768 PreCondVars.restore(CGF);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001769}
1770
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001771void CodeGenFunction::EmitOMPLinearClause(
1772 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1773 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001774 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001775 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1776 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001777 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1778 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001779 SIMDLCVs.insert(
1780 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1781 }
1782 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001783 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001784 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001785 for (const Expr *E : C->varlists()) {
1786 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1787 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001788 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001789 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001790 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001791 // Emit private VarDecl with copy init.
1792 EmitVarDecl(*PrivateVD);
1793 return GetAddrOfLocalVar(PrivateVD);
1794 });
1795 assert(IsRegistered && "linear var already registered as private");
1796 // Silence the warning about unused variable.
1797 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001798 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001799 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001800 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001801 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001802 }
1803 }
1804}
1805
Alexey Bataev45bfad52015-08-21 12:19:04 +00001806static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001807 const OMPExecutableDirective &D,
1808 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001809 if (!CGF.HaveInsertPoint())
1810 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001811 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001812 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1813 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001814 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001815 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1816 // In presence of finite 'safelen', it may be unsafe to mark all
1817 // the memory instructions parallel, because loop-carried
1818 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001819 if (!IsMonotonic)
1820 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001821 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001822 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1823 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001824 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001825 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001826 // In presence of finite 'safelen', it may be unsafe to mark all
1827 // the memory instructions parallel, because loop-carried
1828 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001829 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001830 }
1831}
1832
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001833void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1834 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001835 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001836 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001837 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001838 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001839}
1840
Alexey Bataevef549a82016-03-09 09:49:09 +00001841void CodeGenFunction::EmitOMPSimdFinal(
1842 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001843 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001844 if (!HaveInsertPoint())
1845 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001846 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001847 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001848 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001849 for (const Expr *F : D.finals()) {
1850 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1851 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1852 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001853 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1854 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001855 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001856 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001857 // If the first post-update expression is found, emit conditional
1858 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001859 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001860 DoneBB = createBasicBlock(".omp.final.done");
1861 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1862 EmitBlock(ThenBB);
1863 }
1864 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001865 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001866 if (CED) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001867 OrigAddr =
1868 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001869 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001870 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001871 /*RefersToEnclosingVariableOrCapture=*/false,
1872 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001873 OrigAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001874 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001875 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001876 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001877 (void)VarScope.Privatize();
1878 EmitIgnoredExpr(F);
1879 }
1880 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001881 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001882 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001883 if (DoneBB)
1884 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001885}
1886
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001887static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1888 const OMPLoopDirective &S,
1889 CodeGenFunction::JumpDest LoopExit) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05001890 CGF.CGM.getOpenMPRuntime().initLastprivateConditionalCounter(CGF, S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001891 CGF.EmitOMPLoopBody(S, LoopExit);
1892 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001893}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001894
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001895/// Emit a helper variable and return corresponding lvalue.
1896static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1897 const DeclRefExpr *Helper) {
1898 auto VDecl = cast<VarDecl>(Helper->getDecl());
1899 CGF.EmitVarDecl(*VDecl);
1900 return CGF.EmitLValue(Helper);
1901}
1902
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001903static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
1904 const RegionCodeGenTy &SimdInitGen,
1905 const RegionCodeGenTy &BodyCodeGen) {
Alexey Bataev0860db92019-12-19 10:01:10 -05001906 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
1907 PrePostActionTy &) {
1908 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001909 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1910 SimdInitGen(CGF);
1911
1912 BodyCodeGen(CGF);
1913 };
1914 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
1915 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1916 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
1917
1918 BodyCodeGen(CGF);
1919 };
1920 const Expr *IfCond = nullptr;
1921 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1922 if (CGF.getLangOpts().OpenMP >= 50 &&
1923 (C->getNameModifier() == OMPD_unknown ||
1924 C->getNameModifier() == OMPD_simd)) {
1925 IfCond = C->getCondition();
1926 break;
1927 }
1928 }
1929 if (IfCond) {
1930 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
1931 } else {
1932 RegionCodeGenTy ThenRCG(ThenGen);
1933 ThenRCG(CGF);
1934 }
1935}
1936
Alexey Bataevf8365372017-11-17 17:57:25 +00001937static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1938 PrePostActionTy &Action) {
1939 Action.Enter(CGF);
1940 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1941 "Expected simd directive");
1942 OMPLoopScope PreInitScope(CGF, S);
1943 // if (PreCond) {
1944 // for (IV in 0..LastIteration) BODY;
1945 // <Final counter/linear vars updates>;
1946 // }
1947 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001948 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1949 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1950 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1951 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1952 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1953 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001954
Alexey Bataevf8365372017-11-17 17:57:25 +00001955 // Emit: if (PreCond) - begin.
1956 // If the condition constant folds and can be elided, avoid emitting the
1957 // whole loop.
1958 bool CondConstant;
1959 llvm::BasicBlock *ContBlock = nullptr;
1960 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1961 if (!CondConstant)
1962 return;
1963 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001964 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001965 ContBlock = CGF.createBasicBlock("simd.if.end");
1966 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1967 CGF.getProfileCount(&S));
1968 CGF.EmitBlock(ThenBlock);
1969 CGF.incrementProfileCounter(&S);
1970 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001971
Alexey Bataevf8365372017-11-17 17:57:25 +00001972 // Emit the loop iteration variable.
1973 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001974 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001975 CGF.EmitVarDecl(*IVDecl);
1976 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001977
Alexey Bataevf8365372017-11-17 17:57:25 +00001978 // Emit the iterations count variable.
1979 // If it is not a variable, Sema decided to calculate iterations count on
1980 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001981 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001982 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1983 // Emit calculation of the iterations count.
1984 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1985 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001986
Alexey Bataevf8365372017-11-17 17:57:25 +00001987 emitAlignedClause(CGF, S);
1988 (void)CGF.EmitOMPLinearClauseInit(S);
1989 {
1990 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1991 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1992 CGF.EmitOMPLinearClause(S, LoopScope);
1993 CGF.EmitOMPPrivateClause(S, LoopScope);
1994 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05001995 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
1996 CGF, S, CGF.EmitLValue(S.getIterationVariable()));
Alexey Bataevf8365372017-11-17 17:57:25 +00001997 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1998 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001999 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2000 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevd08c0562019-11-19 12:07:54 -05002001
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002002 emitCommonSimdLoop(
2003 CGF, S,
2004 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2005 CGF.EmitOMPSimdInit(S);
2006 },
2007 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2008 CGF.EmitOMPInnerLoop(
2009 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2010 [&S](CodeGenFunction &CGF) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002011 CGF.CGM.getOpenMPRuntime().initLastprivateConditionalCounter(
2012 CGF, S);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002013 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
2014 CGF.EmitStopPoint(&S);
2015 },
2016 [](CodeGenFunction &) {});
2017 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00002018 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002019 // Emit final copy of the lastprivate variables at the end of loops.
2020 if (HasLastprivateClause)
2021 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2022 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002023 emitPostUpdateForReductionClause(CGF, S,
2024 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002025 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002026 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00002027 // Emit: if (PreCond) - end.
2028 if (ContBlock) {
2029 CGF.EmitBranch(ContBlock);
2030 CGF.EmitBlock(ContBlock, true);
2031 }
2032}
2033
2034void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
2035 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2036 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002037 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002038 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002039 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00002040}
2041
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002042void CodeGenFunction::EmitOMPOuterLoop(
2043 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2044 CodeGenFunction::OMPPrivateScope &LoopScope,
2045 const CodeGenFunction::OMPLoopArguments &LoopArgs,
2046 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2047 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002048 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00002049
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002050 const Expr *IVExpr = S.getIterationVariable();
2051 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2052 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2053
Alexey Bataevddf3db92018-04-13 17:31:06 +00002054 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002055
2056 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002057 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002058 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002059 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00002060 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2061 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002062
2063 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002064 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002065 // UB = min(UB, GlobalUB) or
2066 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2067 // 'distribute parallel for')
2068 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002069 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002070 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002071 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002072 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002073 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002074 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002075 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002076 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002077 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002078
2079 // If there are any cleanups between here and the loop-exit scope,
2080 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002081 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002082 if (LoopScope.requiresCleanups())
2083 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2084
Alexey Bataevddf3db92018-04-13 17:31:06 +00002085 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002086 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2087 if (ExitBlock != LoopExit.getBlock()) {
2088 EmitBlock(ExitBlock);
2089 EmitBranchThroughCleanup(LoopExit);
2090 }
2091 EmitBlock(LoopBody);
2092
Alexander Musman92bdaab2015-03-12 13:37:50 +00002093 // Emit "IV = LB" (in case of static schedule, we have already calculated new
2094 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002095 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002096 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002097
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002098 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002099 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002100 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2101
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002102 emitCommonSimdLoop(
2103 *this, S,
2104 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
2105 // Generate !llvm.loop.parallel metadata for loads and stores for loops
2106 // with dynamic/guided scheduling and without ordered clause.
2107 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
2108 CGF.LoopStack.setParallel(!IsMonotonic);
2109 else
2110 CGF.EmitOMPSimdInit(S, IsMonotonic);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002111 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002112 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2113 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2114 SourceLocation Loc = S.getBeginLoc();
2115 // when 'distribute' is not combined with a 'for':
2116 // while (idx <= UB) { BODY; ++idx; }
2117 // when 'distribute' is combined with a 'for'
2118 // (e.g. 'distribute parallel for')
2119 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2120 CGF.EmitOMPInnerLoop(
2121 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2122 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2123 CodeGenLoop(CGF, S, LoopExit);
2124 },
2125 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2126 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2127 });
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002128 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002129
2130 EmitBlock(Continue.getBlock());
2131 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002132 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002133 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002134 EmitIgnoredExpr(LoopArgs.NextLB);
2135 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002136 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002137
2138 EmitBranch(CondBlock);
2139 LoopStack.pop();
2140 // Emit the fall-through block.
2141 EmitBlock(LoopExit.getBlock());
2142
2143 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002144 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2145 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002146 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002147 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002148 };
2149 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002150}
2151
2152void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002153 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002154 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002155 const OMPLoopArguments &LoopArgs,
2156 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002157 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002158
2159 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002160 const bool DynamicOrOrdered =
2161 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002162
2163 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002164 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002165 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002166 "static non-chunked schedule does not need outer loop");
2167
2168 // Emit outer loop.
2169 //
2170 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2171 // When schedule(dynamic,chunk_size) is specified, the iterations are
2172 // distributed to threads in the team in chunks as the threads request them.
2173 // Each thread executes a chunk of iterations, then requests another chunk,
2174 // until no chunks remain to be distributed. Each chunk contains chunk_size
2175 // iterations, except for the last chunk to be distributed, which may have
2176 // fewer iterations. When no chunk_size is specified, it defaults to 1.
2177 //
2178 // When schedule(guided,chunk_size) is specified, the iterations are assigned
2179 // to threads in the team in chunks as the executing threads request them.
2180 // Each thread executes a chunk of iterations, then requests another chunk,
2181 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2182 // each chunk is proportional to the number of unassigned iterations divided
2183 // by the number of threads in the team, decreasing to 1. For a chunk_size
2184 // with value k (greater than 1), the size of each chunk is determined in the
2185 // same way, with the restriction that the chunks do not contain fewer than k
2186 // iterations (except for the last chunk to be assigned, which may have fewer
2187 // than k iterations).
2188 //
2189 // When schedule(auto) is specified, the decision regarding scheduling is
2190 // delegated to the compiler and/or runtime system. The programmer gives the
2191 // implementation the freedom to choose any possible mapping of iterations to
2192 // threads in the team.
2193 //
2194 // When schedule(runtime) is specified, the decision regarding scheduling is
2195 // deferred until run time, and the schedule and chunk size are taken from the
2196 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2197 // implementation defined
2198 //
2199 // while(__kmpc_dispatch_next(&LB, &UB)) {
2200 // idx = LB;
2201 // while (idx <= UB) { BODY; ++idx;
2202 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2203 // } // inner loop
2204 // }
2205 //
2206 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2207 // When schedule(static, chunk_size) is specified, iterations are divided into
2208 // chunks of size chunk_size, and the chunks are assigned to the threads in
2209 // the team in a round-robin fashion in the order of the thread number.
2210 //
2211 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2212 // while (idx <= UB) { BODY; ++idx; } // inner loop
2213 // LB = LB + ST;
2214 // UB = UB + ST;
2215 // }
2216 //
2217
2218 const Expr *IVExpr = S.getIterationVariable();
2219 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2220 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2221
2222 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002223 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2224 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002225 llvm::Value *LBVal = DispatchBounds.first;
2226 llvm::Value *UBVal = DispatchBounds.second;
2227 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2228 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002229 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002230 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002231 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002232 CGOpenMPRuntime::StaticRTInput StaticInit(
2233 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2234 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002235 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002236 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002237 }
2238
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002239 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2240 const unsigned IVSize,
2241 const bool IVSigned) {
2242 if (Ordered) {
2243 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2244 IVSigned);
2245 }
2246 };
2247
2248 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2249 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2250 OuterLoopArgs.IncExpr = S.getInc();
2251 OuterLoopArgs.Init = S.getInit();
2252 OuterLoopArgs.Cond = S.getCond();
2253 OuterLoopArgs.NextLB = S.getNextLowerBound();
2254 OuterLoopArgs.NextUB = S.getNextUpperBound();
2255 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2256 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002257}
2258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002259static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2260 const unsigned IVSize, const bool IVSigned) {}
2261
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002262void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002263 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2264 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2265 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002266
Alexey Bataevddf3db92018-04-13 17:31:06 +00002267 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002268
2269 // Emit outer loop.
2270 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2271 // dynamic
2272 //
2273
2274 const Expr *IVExpr = S.getIterationVariable();
2275 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2276 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2277
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002278 CGOpenMPRuntime::StaticRTInput StaticInit(
2279 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2280 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002281 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002282
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002283 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002284 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002285 Expr *IncExpr;
2286 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2287 IncExpr = S.getDistInc();
2288 else
2289 IncExpr = S.getInc();
2290
2291 // this routine is shared by 'omp distribute parallel for' and
2292 // 'omp distribute': select the right EUB expression depending on the
2293 // directive
2294 OMPLoopArguments OuterLoopArgs;
2295 OuterLoopArgs.LB = LoopArgs.LB;
2296 OuterLoopArgs.UB = LoopArgs.UB;
2297 OuterLoopArgs.ST = LoopArgs.ST;
2298 OuterLoopArgs.IL = LoopArgs.IL;
2299 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2300 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2301 ? S.getCombinedEnsureUpperBound()
2302 : S.getEnsureUpperBound();
2303 OuterLoopArgs.IncExpr = IncExpr;
2304 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2305 ? S.getCombinedInit()
2306 : S.getInit();
2307 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2308 ? S.getCombinedCond()
2309 : S.getCond();
2310 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2311 ? S.getCombinedNextLowerBound()
2312 : S.getNextLowerBound();
2313 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2314 ? S.getCombinedNextUpperBound()
2315 : S.getNextUpperBound();
2316
2317 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2318 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2319 emitEmptyOrdered);
2320}
2321
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002322static std::pair<LValue, LValue>
2323emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2324 const OMPExecutableDirective &S) {
2325 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2326 LValue LB =
2327 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2328 LValue UB =
2329 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2330
2331 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2332 // parallel for') we need to use the 'distribute'
2333 // chunk lower and upper bounds rather than the whole loop iteration
2334 // space. These are parameters to the outlined function for 'parallel'
2335 // and we copy the bounds of the previous schedule into the
2336 // the current ones.
2337 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2338 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002339 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2340 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002341 PrevLBVal = CGF.EmitScalarConversion(
2342 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002343 LS.getIterationVariable()->getType(),
2344 LS.getPrevLowerBoundVariable()->getExprLoc());
2345 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2346 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002347 PrevUBVal = CGF.EmitScalarConversion(
2348 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002349 LS.getIterationVariable()->getType(),
2350 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002351
2352 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2353 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2354
2355 return {LB, UB};
2356}
2357
2358/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2359/// we need to use the LB and UB expressions generated by the worksharing
2360/// code generation support, whereas in non combined situations we would
2361/// just emit 0 and the LastIteration expression
2362/// This function is necessary due to the difference of the LB and UB
2363/// types for the RT emission routines for 'for_static_init' and
2364/// 'for_dispatch_init'
2365static std::pair<llvm::Value *, llvm::Value *>
2366emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2367 const OMPExecutableDirective &S,
2368 Address LB, Address UB) {
2369 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2370 const Expr *IVExpr = LS.getIterationVariable();
2371 // when implementing a dynamic schedule for a 'for' combined with a
2372 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2373 // is not normalized as each team only executes its own assigned
2374 // distribute chunk
2375 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002376 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002377 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002378 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002379 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002380 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002381}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002382
2383static void emitDistributeParallelForDistributeInnerBoundParams(
2384 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2385 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2386 const auto &Dir = cast<OMPLoopDirective>(S);
2387 LValue LB =
2388 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002389 llvm::Value *LBCast =
2390 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
2391 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002392 CapturedVars.push_back(LBCast);
2393 LValue UB =
2394 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2395
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002396 llvm::Value *UBCast =
2397 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
2398 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002399 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002400}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002401
2402static void
2403emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2404 const OMPLoopDirective &S,
2405 CodeGenFunction::JumpDest LoopExit) {
2406 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002407 PrePostActionTy &Action) {
2408 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002409 bool HasCancel = false;
2410 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2411 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2412 HasCancel = D->hasCancel();
2413 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2414 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002415 else if (const auto *D =
2416 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2417 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002418 }
2419 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2420 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002421 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2422 emitDistributeParallelForInnerBounds,
2423 emitDistributeParallelForDispatchBounds);
2424 };
2425
2426 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002427 CGF, S,
2428 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2429 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002430 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002431}
2432
Carlo Bertolli9925f152016-06-27 14:55:37 +00002433void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2434 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002435 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2436 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2437 S.getDistInc());
2438 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002439 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002440 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002441}
2442
Kelvin Li4a39add2016-07-05 05:00:15 +00002443void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2444 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002445 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2446 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2447 S.getDistInc());
2448 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002449 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002450 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002451}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002452
2453void CodeGenFunction::EmitOMPDistributeSimdDirective(
2454 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002455 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2456 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2457 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002458 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002459 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002460}
2461
Alexey Bataevf8365372017-11-17 17:57:25 +00002462void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2463 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2464 // Emit SPMD target parallel for region as a standalone region.
2465 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2466 emitOMPSimdRegion(CGF, S, Action);
2467 };
2468 llvm::Function *Fn;
2469 llvm::Constant *Addr;
2470 // Emit target region as a standalone region.
2471 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2472 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2473 assert(Fn && Addr && "Target device function emission failed.");
2474}
2475
Kelvin Li986330c2016-07-20 22:57:10 +00002476void CodeGenFunction::EmitOMPTargetSimdDirective(
2477 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002478 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2479 emitOMPSimdRegion(CGF, S, Action);
2480 };
2481 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002482}
2483
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002484namespace {
2485 struct ScheduleKindModifiersTy {
2486 OpenMPScheduleClauseKind Kind;
2487 OpenMPScheduleClauseModifier M1;
2488 OpenMPScheduleClauseModifier M2;
2489 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2490 OpenMPScheduleClauseModifier M1,
2491 OpenMPScheduleClauseModifier M2)
2492 : Kind(Kind), M1(M1), M2(M2) {}
2493 };
2494} // namespace
2495
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002496bool CodeGenFunction::EmitOMPWorksharingLoop(
2497 const OMPLoopDirective &S, Expr *EUB,
2498 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2499 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002500 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002501 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2502 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002503 EmitVarDecl(*IVDecl);
2504
2505 // Emit the iterations count variable.
2506 // If it is not a variable, Sema decided to calculate iterations count on each
2507 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002508 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002509 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2510 // Emit calculation of the iterations count.
2511 EmitIgnoredExpr(S.getCalcLastIteration());
2512 }
2513
Alexey Bataevddf3db92018-04-13 17:31:06 +00002514 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002515
Alexey Bataev38e89532015-04-16 04:54:05 +00002516 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002517 // Check pre-condition.
2518 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002519 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002520 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002521 // If the condition constant folds and can be elided, avoid emitting the
2522 // whole loop.
2523 bool CondConstant;
2524 llvm::BasicBlock *ContBlock = nullptr;
2525 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2526 if (!CondConstant)
2527 return false;
2528 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002529 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002530 ContBlock = createBasicBlock("omp.precond.end");
2531 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002532 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002533 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002534 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002535 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002536
Alexey Bataevea33dee2018-02-15 23:39:43 +00002537 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002538 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002539 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002540 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002541 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002542 else
2543 Ordered = true;
2544 }
2545
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002546 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002547 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002548 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002549 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002550
2551 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2552 LValue LB = Bounds.first;
2553 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002554 LValue ST =
2555 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2556 LValue IL =
2557 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2558
Alexander Musmanc6388682014-12-15 07:07:06 +00002559 // Emit 'then' code.
2560 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002561 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002562 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002563 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002564 // initialization of firstprivate variables and post-update of
2565 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002566 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002567 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002568 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002569 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002570 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05002571 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2572 *this, S, EmitLValue(S.getIterationVariable()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002573 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002574 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002575 EmitOMPPrivateLoopCounters(S, LoopScope);
2576 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002577 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002578 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2579 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002580
2581 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002582 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002583 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002584 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002585 ScheduleKind.Schedule = C->getScheduleKind();
2586 ScheduleKind.M1 = C->getFirstScheduleModifier();
2587 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002588 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002589 } else {
2590 // Default behaviour for schedule clause.
2591 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002592 *this, S, ScheduleKind.Schedule, ChunkExpr);
2593 }
2594 bool HasChunkSizeOne = false;
2595 llvm::Value *Chunk = nullptr;
2596 if (ChunkExpr) {
2597 Chunk = EmitScalarExpr(ChunkExpr);
2598 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2599 S.getIterationVariable()->getType(),
2600 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002601 Expr::EvalResult Result;
2602 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2603 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002604 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002605 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002606 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002607 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2608 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002609 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2610 // If the static schedule kind is specified or if the ordered clause is
2611 // specified, and if no monotonic modifier is specified, the effect will
2612 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002613 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2614 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2615 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2616 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2617 /* Chunked */ Chunk != nullptr) ||
2618 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002619 !Ordered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002620 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002621 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002622 emitCommonSimdLoop(
2623 *this, S,
2624 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2625 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2626 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002627 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002628 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2629 &S, ScheduleKind, LoopExit,
2630 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2631 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2632 // When no chunk_size is specified, the iteration space is divided
2633 // into chunks that are approximately equal in size, and at most
2634 // one chunk is distributed to each thread. Note that the size of
2635 // the chunks is unspecified in this case.
2636 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002637 IVSize, IVSigned, Ordered, IL.getAddress(CGF),
2638 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002639 StaticChunkedOne ? Chunk : nullptr);
2640 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2641 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2642 StaticInit);
2643 // UB = min(UB, GlobalUB);
2644 if (!StaticChunkedOne)
2645 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2646 // IV = LB;
2647 CGF.EmitIgnoredExpr(S.getInit());
2648 // For unchunked static schedule generate:
2649 //
2650 // while (idx <= UB) {
2651 // BODY;
2652 // ++idx;
2653 // }
2654 //
2655 // For static schedule with chunk one:
2656 //
2657 // while (IV <= PrevUB) {
2658 // BODY;
2659 // IV += ST;
2660 // }
2661 CGF.EmitOMPInnerLoop(
2662 S, LoopScope.requiresCleanups(),
2663 StaticChunkedOne ? S.getCombinedParForInDistCond()
2664 : S.getCond(),
2665 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2666 [&S, LoopExit](CodeGenFunction &CGF) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002667 CGF.CGM.getOpenMPRuntime()
2668 .initLastprivateConditionalCounter(CGF, S);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002669 CGF.EmitOMPLoopBody(S, LoopExit);
2670 CGF.EmitStopPoint(&S);
2671 },
2672 [](CodeGenFunction &) {});
2673 });
Alexey Bataev0f34da12015-07-02 04:17:07 +00002674 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002675 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002676 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002677 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002678 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002679 };
2680 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002681 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002682 const bool IsMonotonic =
2683 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2684 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2685 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2686 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002687 // Emit the outer loop, which requests its work chunk [LB..UB] from
2688 // runtime and runs the inner loop to process it.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002689 const OMPLoopArguments LoopArguments(
2690 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
2691 IL.getAddress(*this), Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002692 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002693 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002694 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002695 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002696 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2697 return CGF.Builder.CreateIsNotNull(
2698 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2699 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002700 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002701 EmitOMPReductionClauseFinal(
2702 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2703 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2704 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002705 // Emit post-update of the reduction variables if IsLastIter != 0.
2706 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002707 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002708 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002710 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002711 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2712 if (HasLastprivateClause)
2713 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002714 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002715 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002716 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002717 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002718 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002719 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002720 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002721 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002722 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002723 if (ContBlock) {
2724 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002725 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002726 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002727 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002728 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002729}
2730
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002731/// The following two functions generate expressions for the loop lower
2732/// and upper bounds in case of static and dynamic (dispatch) schedule
2733/// of the associated 'for' or 'distribute' loop.
2734static std::pair<LValue, LValue>
2735emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002736 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002737 LValue LB =
2738 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2739 LValue UB =
2740 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2741 return {LB, UB};
2742}
2743
2744/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2745/// consider the lower and upper bound expressions generated by the
2746/// worksharing loop support, but we use 0 and the iteration space size as
2747/// constants
2748static std::pair<llvm::Value *, llvm::Value *>
2749emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2750 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002751 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002752 const Expr *IVExpr = LS.getIterationVariable();
2753 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2754 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2755 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2756 return {LBVal, UBVal};
2757}
2758
Alexander Musmanc6388682014-12-15 07:07:06 +00002759void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002760 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002761 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2762 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002763 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002764 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2765 emitForLoopBounds,
2766 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002767 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002768 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002769 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002770 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2771 S.hasCancel());
2772 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002773
2774 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002775 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002776 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002777}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002778
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002779void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002780 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002781 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2782 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002783 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2784 emitForLoopBounds,
2785 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002786 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002787 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002788 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002789 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2790 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002791
2792 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002793 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002794 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002795}
2796
Alexey Bataev2df54a02015-03-12 08:53:29 +00002797static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2798 const Twine &Name,
2799 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002800 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002801 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002802 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002803 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002804}
2805
Alexey Bataev3392d762016-02-16 11:18:12 +00002806void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002807 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2808 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002809 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002810 auto &&CodeGen = [&S, CapturedStmt, CS,
2811 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2812 ASTContext &C = CGF.getContext();
2813 QualType KmpInt32Ty =
2814 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002815 // Emit helper vars inits.
2816 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2817 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002818 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2819 ? CGF.Builder.getInt32(CS->size() - 1)
2820 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002821 LValue UB =
2822 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2823 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2824 CGF.Builder.getInt32(1));
2825 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2826 CGF.Builder.getInt32(0));
2827 // Loop counter.
2828 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002829 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002830 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002831 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002832 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2833 // Generate condition for loop.
2834 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002835 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002836 // Increment for loop counter.
2837 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002838 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002839 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002840 // Iterate through all sections and emit a switch construct:
2841 // switch (IV) {
2842 // case 0:
2843 // <SectionStmt[0]>;
2844 // break;
2845 // ...
2846 // case <NumSection> - 1:
2847 // <SectionStmt[<NumSection> - 1]>;
2848 // break;
2849 // }
2850 // .omp.sections.exit:
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002851 CGF.CGM.getOpenMPRuntime().initLastprivateConditionalCounter(CGF, S);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002852 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2853 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002854 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002855 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002856 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002857 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002858 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002859 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2860 CGF.EmitBlock(CaseBB);
2861 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002862 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002863 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002864 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002865 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002866 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002867 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002868 CGF.EmitBlock(CaseBB);
2869 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002870 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002871 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002872 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002873 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002874 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002875
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002876 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2877 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002878 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002879 // initialization of firstprivate variables and post-update of lastprivate
2880 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002881 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002882 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002883 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002884 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002885 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05002886 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002887 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2888 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2889 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002890 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2891 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002892
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002893 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002894 OpenMPScheduleTy ScheduleKind;
2895 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002896 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002897 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
2898 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002899 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002900 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002901 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002902 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002903 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002904 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2905 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2906 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002907 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002908 // while (idx <= UB) { BODY; ++idx; }
2909 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2910 [](CodeGenFunction &) {});
2911 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002912 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002913 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002914 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002915 };
2916 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002918 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002919 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2920 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002921 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002922 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002923
2924 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2925 if (HasLastprivates)
2926 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002927 S, /*NoFinals=*/false,
2928 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002929 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002930 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002931
2932 bool HasCancel = false;
2933 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2934 HasCancel = OSD->hasCancel();
2935 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2936 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002937 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002938 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2939 HasCancel);
2940 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2941 // clause. Otherwise the barrier will be generated by the codegen for the
2942 // directive.
2943 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002944 // Emit implicit barrier to synchronize threads and avoid data races on
2945 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002946 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002947 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002948 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002949}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002950
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002951void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002952 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002953 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002954 EmitSections(S);
2955 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002956 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002957 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002958 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002959 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002960 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002961}
2962
2963void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002964 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002965 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002966 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002967 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002968 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2969 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002970}
2971
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002972void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002973 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002974 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002975 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002976 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002977 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002978 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002979 // Build a list of copyprivate variables along with helper expressions
2980 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002981 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002982 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002983 DestExprs.append(C->destination_exprs().begin(),
2984 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002985 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002986 AssignmentOps.append(C->assignment_ops().begin(),
2987 C->assignment_ops().end());
2988 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002989 // Emit code for 'single' region along with 'copyprivate' clauses
2990 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2991 Action.Enter(CGF);
2992 OMPPrivateScope SingleScope(CGF);
2993 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2994 CGF.EmitOMPPrivateClause(S, SingleScope);
2995 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002996 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002997 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002998 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002999 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003000 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00003001 CopyprivateVars, DestExprs,
3002 SrcExprs, AssignmentOps);
3003 }
3004 // Emit an implicit barrier at the end (to avoid data race on firstprivate
3005 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00003006 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00003007 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003008 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003009 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00003010 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003011}
3012
cchen47d60942019-12-05 13:43:48 -05003013static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003014 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3015 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003016 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003017 };
cchen47d60942019-12-05 13:43:48 -05003018 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3019}
3020
3021void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003022 OMPLexicalScope Scope(*this, S, OMPD_unknown);
cchen47d60942019-12-05 13:43:48 -05003023 emitMaster(*this, S);
Alexander Musman80c22892014-07-17 08:54:58 +00003024}
3025
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003026void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003027 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3028 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003029 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003030 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003031 const Expr *Hint = nullptr;
3032 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00003033 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00003034 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003035 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
3036 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003037 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003038}
3039
Alexey Bataev671605e2015-04-13 05:28:11 +00003040void CodeGenFunction::EmitOMPParallelForDirective(
3041 const OMPParallelForDirective &S) {
3042 // Emit directive as a combined directive that consists of two implicit
3043 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003044 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3045 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00003046 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003047 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3048 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00003049 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003050 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
3051 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003052}
3053
Alexander Musmane4e893b2014-09-23 09:33:00 +00003054void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003055 const OMPParallelForSimdDirective &S) {
3056 // Emit directive as a combined directive that consists of two implicit
3057 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003058 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3059 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003060 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3061 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003062 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003063 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
3064 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003065}
3066
cchen47d60942019-12-05 13:43:48 -05003067void CodeGenFunction::EmitOMPParallelMasterDirective(
3068 const OMPParallelMasterDirective &S) {
3069 // Emit directive as a combined directive that consists of two implicit
3070 // directives: 'parallel' with 'master' directive.
3071 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3072 Action.Enter(CGF);
3073 OMPPrivateScope PrivateScope(CGF);
3074 bool Copyins = CGF.EmitOMPCopyinClause(S);
3075 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3076 if (Copyins) {
3077 // Emit implicit barrier to synchronize threads and avoid data races on
3078 // propagation master's thread values of threadprivate variables to local
3079 // instances of that variables of all other implicit threads.
3080 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3081 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3082 /*ForceSimpleCall=*/true);
3083 }
3084 CGF.EmitOMPPrivateClause(S, PrivateScope);
3085 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3086 (void)PrivateScope.Privatize();
3087 emitMaster(CGF, S);
3088 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3089 };
3090 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
3091 emitEmptyBoundParameters);
3092 emitPostUpdateForReductionClause(*this, S,
3093 [](CodeGenFunction &) { return nullptr; });
3094}
3095
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003096void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00003097 const OMPParallelSectionsDirective &S) {
3098 // Emit directive as a combined directive that consists of two implicit
3099 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00003100 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3101 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003102 CGF.EmitSections(S);
3103 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003104 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
3105 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003106}
3107
Alexey Bataev475a7442018-01-12 19:39:11 +00003108void CodeGenFunction::EmitOMPTaskBasedDirective(
3109 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
3110 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
3111 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003112 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003113 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003114 auto I = CS->getCapturedDecl()->param_begin();
3115 auto PartId = std::next(I);
3116 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003117 // Check if the task is final
3118 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3119 // If the condition constant folds and can be elided, try to avoid emitting
3120 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003121 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003122 bool CondConstant;
3123 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3124 Data.Final.setInt(CondConstant);
3125 else
3126 Data.Final.setPointer(EvaluateExprAsBool(Cond));
3127 } else {
3128 // By default the task is not final.
3129 Data.Final.setInt(/*IntVal=*/false);
3130 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003131 // Check if the task has 'priority' clause.
3132 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003133 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00003134 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003135 Data.Priority.setPointer(EmitScalarConversion(
3136 EmitScalarExpr(Prio), Prio->getType(),
3137 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3138 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003139 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003140 // The first function argument for tasks is a thread id, the second one is a
3141 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003142 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
3143 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003144 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003145 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003146 for (const Expr *IInit : C->private_copies()) {
3147 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003148 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003149 Data.PrivateVars.push_back(*IRef);
3150 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003151 }
3152 ++IRef;
3153 }
3154 }
3155 EmittedAsPrivate.clear();
3156 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003157 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003158 auto IRef = C->varlist_begin();
3159 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003160 for (const Expr *IInit : C->private_copies()) {
3161 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003162 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003163 Data.FirstprivateVars.push_back(*IRef);
3164 Data.FirstprivateCopies.push_back(IInit);
3165 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003166 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003167 ++IRef;
3168 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003169 }
3170 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003171 // Get list of lastprivate variables (for taskloops).
3172 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3173 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3174 auto IRef = C->varlist_begin();
3175 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003176 for (const Expr *IInit : C->private_copies()) {
3177 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003178 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3179 Data.LastprivateVars.push_back(*IRef);
3180 Data.LastprivateCopies.push_back(IInit);
3181 }
3182 LastprivateDstsOrigs.insert(
3183 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3184 cast<DeclRefExpr>(*IRef)});
3185 ++IRef;
3186 ++ID;
3187 }
3188 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003189 SmallVector<const Expr *, 4> LHSs;
3190 SmallVector<const Expr *, 4> RHSs;
3191 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3192 auto IPriv = C->privates().begin();
3193 auto IRed = C->reduction_ops().begin();
3194 auto ILHS = C->lhs_exprs().begin();
3195 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003196 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003197 Data.ReductionVars.emplace_back(Ref);
3198 Data.ReductionCopies.emplace_back(*IPriv);
3199 Data.ReductionOps.emplace_back(*IRed);
3200 LHSs.emplace_back(*ILHS);
3201 RHSs.emplace_back(*IRHS);
3202 std::advance(IPriv, 1);
3203 std::advance(IRed, 1);
3204 std::advance(ILHS, 1);
3205 std::advance(IRHS, 1);
3206 }
3207 }
3208 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003209 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003210 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00003211 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003212 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003213 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00003214 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3215 CapturedRegion](CodeGenFunction &CGF,
3216 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003217 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00003218 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003219 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3220 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003221 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3222 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003223 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003224 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3225 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3226 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3227 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00003228 // Map privates.
3229 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3230 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3231 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003232 for (const Expr *E : Data.PrivateVars) {
3233 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003234 Address PrivatePtr = CGF.CreateMemTemp(
3235 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003236 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003237 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003238 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003239 for (const Expr *E : Data.FirstprivateVars) {
3240 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003241 Address PrivatePtr =
3242 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3243 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003244 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003245 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003246 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003247 for (const Expr *E : Data.LastprivateVars) {
3248 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003249 Address PrivatePtr =
3250 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3251 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003252 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003253 CallArgs.push_back(PrivatePtr.getPointer());
3254 }
James Y Knight9871db02019-02-05 16:42:33 +00003255 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3256 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003257 for (const auto &Pair : LastprivateDstsOrigs) {
3258 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003259 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3260 /*RefersToEnclosingVariableOrCapture=*/
3261 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3262 Pair.second->getType(), VK_LValue,
3263 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003264 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003265 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003266 });
3267 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003268 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003269 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3270 CGF.getContext().getDeclAlign(Pair.first));
3271 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3272 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003273 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003274 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003275 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003276 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3277 Data.ReductionOps);
3278 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3279 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3280 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3281 RedCG.emitSharedLValue(CGF, Cnt);
3282 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003283 // FIXME: This must removed once the runtime library is fixed.
3284 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003285 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003286 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003287 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003288 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003289 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003290 Replacement =
3291 Address(CGF.EmitScalarConversion(
3292 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3293 CGF.getContext().getPointerType(
3294 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003295 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003296 Replacement.getAlignment());
3297 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3298 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3299 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003300 }
3301 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003302 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003303 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003304 SmallVector<const Expr *, 4> InRedVars;
3305 SmallVector<const Expr *, 4> InRedPrivs;
3306 SmallVector<const Expr *, 4> InRedOps;
3307 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3308 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3309 auto IPriv = C->privates().begin();
3310 auto IRed = C->reduction_ops().begin();
3311 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003312 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003313 InRedVars.emplace_back(Ref);
3314 InRedPrivs.emplace_back(*IPriv);
3315 InRedOps.emplace_back(*IRed);
3316 TaskgroupDescriptors.emplace_back(*ITD);
3317 std::advance(IPriv, 1);
3318 std::advance(IRed, 1);
3319 std::advance(ITD, 1);
3320 }
3321 }
3322 // Privatize in_reduction items here, because taskgroup descriptors must be
3323 // privatized earlier.
3324 OMPPrivateScope InRedScope(CGF);
3325 if (!InRedVars.empty()) {
3326 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3327 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3328 RedCG.emitSharedLValue(CGF, Cnt);
3329 RedCG.emitAggregateType(CGF, Cnt);
3330 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003331 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003332 // FIXME: This must removed once the runtime library is fixed.
3333 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003334 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003335 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003336 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003337 llvm::Value *ReductionsPtr =
3338 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3339 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003340 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003341 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003342 Replacement = Address(
3343 CGF.EmitScalarConversion(
3344 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3345 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003346 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003347 Replacement.getAlignment());
3348 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3349 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3350 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003351 }
3352 }
3353 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003354
3355 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003356 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003357 };
James Y Knight9871db02019-02-05 16:42:33 +00003358 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003359 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3360 Data.NumberOfParts);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003361 OMPLexicalScope Scope(*this, S, llvm::None,
Alexey Bataev61205822019-12-04 09:50:21 -05003362 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3363 !isOpenMPSimdDirective(S.getDirectiveKind()));
Alexey Bataev7292c292016-04-25 12:22:29 +00003364 TaskGen(*this, OutlinedFn, Data);
3365}
3366
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003367static ImplicitParamDecl *
3368createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003369 QualType Ty, CapturedDecl *CD,
3370 SourceLocation Loc) {
3371 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3372 ImplicitParamDecl::Other);
3373 auto *OrigRef = DeclRefExpr::Create(
3374 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3375 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3376 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3377 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003378 auto *PrivateRef = DeclRefExpr::Create(
3379 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003380 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003381 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003382 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3383 ImplicitParamDecl::Other);
3384 auto *InitRef = DeclRefExpr::Create(
3385 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3386 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003387 PrivateVD->setInitStyle(VarDecl::CInit);
3388 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3389 InitRef, /*BasePath=*/nullptr,
3390 VK_RValue));
3391 Data.FirstprivateVars.emplace_back(OrigRef);
3392 Data.FirstprivateCopies.emplace_back(PrivateRef);
3393 Data.FirstprivateInits.emplace_back(InitRef);
3394 return OrigVD;
3395}
3396
3397void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3398 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3399 OMPTargetDataInfo &InputInfo) {
3400 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003401 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3402 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3403 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3404 auto I = CS->getCapturedDecl()->param_begin();
3405 auto PartId = std::next(I);
3406 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003407 OMPTaskDataTy Data;
3408 // The task is not final.
3409 Data.Final.setInt(/*IntVal=*/false);
3410 // Get list of firstprivate variables.
3411 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3412 auto IRef = C->varlist_begin();
3413 auto IElemInitRef = C->inits().begin();
3414 for (auto *IInit : C->private_copies()) {
3415 Data.FirstprivateVars.push_back(*IRef);
3416 Data.FirstprivateCopies.push_back(IInit);
3417 Data.FirstprivateInits.push_back(*IElemInitRef);
3418 ++IRef;
3419 ++IElemInitRef;
3420 }
3421 }
3422 OMPPrivateScope TargetScope(*this);
3423 VarDecl *BPVD = nullptr;
3424 VarDecl *PVD = nullptr;
3425 VarDecl *SVD = nullptr;
3426 if (InputInfo.NumberOfTargetItems > 0) {
3427 auto *CD = CapturedDecl::Create(
3428 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3429 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3430 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003431 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003432 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003433 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003434 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003435 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003436 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003437 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003438 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003439 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003440 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003441 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003442 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003443 TargetScope.addPrivate(
3444 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3445 TargetScope.addPrivate(PVD,
3446 [&InputInfo]() { return InputInfo.PointersArray; });
3447 TargetScope.addPrivate(SVD,
3448 [&InputInfo]() { return InputInfo.SizesArray; });
3449 }
3450 (void)TargetScope.Privatize();
3451 // Build list of dependences.
3452 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003453 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003454 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003455 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3456 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3457 // Set proper addresses for generated private copies.
3458 OMPPrivateScope Scope(CGF);
3459 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003460 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3461 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003462 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003463 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3464 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3465 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3466 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003467 // Map privates.
3468 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3469 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3470 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003471 for (const Expr *E : Data.FirstprivateVars) {
3472 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003473 Address PrivatePtr =
3474 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3475 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003476 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003477 CallArgs.push_back(PrivatePtr.getPointer());
3478 }
James Y Knight9871db02019-02-05 16:42:33 +00003479 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3480 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003481 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003482 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3483 CGF.getContext().getDeclAlign(Pair.first));
3484 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3485 }
3486 }
3487 // Privatize all private variables except for in_reduction items.
3488 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003489 if (InputInfo.NumberOfTargetItems > 0) {
3490 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003491 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003492 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003493 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003494 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003495 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003496 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003497
3498 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003499 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003500 BodyGen(CGF);
3501 };
James Y Knight9871db02019-02-05 16:42:33 +00003502 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003503 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3504 Data.NumberOfParts);
3505 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3506 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3507 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3508 SourceLocation());
3509
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003510 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003511 SharedsTy, CapturedStruct, &IfCond, Data);
3512}
3513
Alexey Bataev7292c292016-04-25 12:22:29 +00003514void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3515 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003516 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003517 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3518 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003519 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003520 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3521 if (C->getNameModifier() == OMPD_unknown ||
3522 C->getNameModifier() == OMPD_task) {
3523 IfCond = C->getCondition();
3524 break;
3525 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003526 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003527
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003528 OMPTaskDataTy Data;
3529 // Check if we should emit tied or untied task.
3530 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003531 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3532 CGF.EmitStmt(CS->getCapturedStmt());
3533 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003534 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003535 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003536 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003537 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003538 SharedsTy, CapturedStruct, IfCond,
3539 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003540 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003541 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003542}
3543
Alexey Bataev9f797f32015-02-05 05:57:51 +00003544void CodeGenFunction::EmitOMPTaskyieldDirective(
3545 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003546 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003547}
3548
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003549void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003550 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003551}
3552
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003553void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003554 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003555}
3556
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003557void CodeGenFunction::EmitOMPTaskgroupDirective(
3558 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003559 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3560 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003561 if (const Expr *E = S.getReductionRef()) {
3562 SmallVector<const Expr *, 4> LHSs;
3563 SmallVector<const Expr *, 4> RHSs;
3564 OMPTaskDataTy Data;
3565 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3566 auto IPriv = C->privates().begin();
3567 auto IRed = C->reduction_ops().begin();
3568 auto ILHS = C->lhs_exprs().begin();
3569 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003570 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003571 Data.ReductionVars.emplace_back(Ref);
3572 Data.ReductionCopies.emplace_back(*IPriv);
3573 Data.ReductionOps.emplace_back(*IRed);
3574 LHSs.emplace_back(*ILHS);
3575 RHSs.emplace_back(*IRHS);
3576 std::advance(IPriv, 1);
3577 std::advance(IRed, 1);
3578 std::advance(ILHS, 1);
3579 std::advance(IRHS, 1);
3580 }
3581 }
3582 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003583 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003584 LHSs, RHSs, Data);
3585 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3586 CGF.EmitVarDecl(*VD);
3587 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3588 /*Volatile=*/false, E->getType());
3589 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003590 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003591 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003592 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003593 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003594}
3595
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003596void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003597 CGM.getOpenMPRuntime().emitFlush(
3598 *this,
3599 [&S]() -> ArrayRef<const Expr *> {
3600 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3601 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3602 FlushClause->varlist_end());
3603 return llvm::None;
3604 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003605 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003606}
3607
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003608void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3609 const CodeGenLoopTy &CodeGenLoop,
3610 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003611 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003612 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3613 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003614 EmitVarDecl(*IVDecl);
3615
3616 // Emit the iterations count variable.
3617 // If it is not a variable, Sema decided to calculate iterations count on each
3618 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003619 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003620 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3621 // Emit calculation of the iterations count.
3622 EmitIgnoredExpr(S.getCalcLastIteration());
3623 }
3624
Alexey Bataevddf3db92018-04-13 17:31:06 +00003625 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003626
Carlo Bertolli962bb802017-01-03 18:24:42 +00003627 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003628 // Check pre-condition.
3629 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003630 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003631 // Skip the entire loop if we don't meet the precondition.
3632 // If the condition constant folds and can be elided, avoid emitting the
3633 // whole loop.
3634 bool CondConstant;
3635 llvm::BasicBlock *ContBlock = nullptr;
3636 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3637 if (!CondConstant)
3638 return;
3639 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003640 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003641 ContBlock = createBasicBlock("omp.precond.end");
3642 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3643 getProfileCount(&S));
3644 EmitBlock(ThenBlock);
3645 incrementProfileCounter(&S);
3646 }
3647
Alexey Bataev617db5f2017-12-04 15:38:33 +00003648 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003649 // Emit 'then' code.
3650 {
3651 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003652
3653 LValue LB = EmitOMPHelperVar(
3654 *this, cast<DeclRefExpr>(
3655 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3656 ? S.getCombinedLowerBoundVariable()
3657 : S.getLowerBoundVariable())));
3658 LValue UB = EmitOMPHelperVar(
3659 *this, cast<DeclRefExpr>(
3660 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3661 ? S.getCombinedUpperBoundVariable()
3662 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003663 LValue ST =
3664 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3665 LValue IL =
3666 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3667
3668 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003669 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003670 // Emit implicit barrier to synchronize threads and avoid data races
3671 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003672 // lastprivate variables.
3673 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003674 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003675 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003676 }
3677 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003678 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003679 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3680 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003681 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003682 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003683 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003684 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003685 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3686 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003687
3688 // Detect the distribute schedule kind and chunk.
3689 llvm::Value *Chunk = nullptr;
3690 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003691 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003692 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003693 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003694 Chunk = EmitScalarExpr(Ch);
3695 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003696 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003697 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003698 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003699 } else {
3700 // Default behaviour for dist_schedule clause.
3701 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3702 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003703 }
3704 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3705 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3706
3707 // OpenMP [2.10.8, distribute Construct, Description]
3708 // If dist_schedule is specified, kind must be static. If specified,
3709 // iterations are divided into chunks of size chunk_size, chunks are
3710 // assigned to the teams of the league in a round-robin fashion in the
3711 // order of the team number. When no chunk_size is specified, the
3712 // iteration space is divided into chunks that are approximately equal
3713 // in size, and at most one chunk is distributed to each team of the
3714 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003715 bool StaticChunked = RT.isStaticChunked(
3716 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3717 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003718 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003719 /* Chunked */ Chunk != nullptr) ||
3720 StaticChunked) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003721 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003722 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
3723 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003724 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003725 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003726 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003727 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003728 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3729 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003730 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3731 ? S.getCombinedEnsureUpperBound()
3732 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003733 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003734 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3735 ? S.getCombinedInit()
3736 : S.getInit());
3737
Alexey Bataevddf3db92018-04-13 17:31:06 +00003738 const Expr *Cond =
3739 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3740 ? S.getCombinedCond()
3741 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003742
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003743 if (StaticChunked)
3744 Cond = S.getCombinedDistCond();
3745
3746 // For static unchunked schedules generate:
3747 //
3748 // 1. For distribute alone, codegen
3749 // while (idx <= UB) {
3750 // BODY;
3751 // ++idx;
3752 // }
3753 //
3754 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3755 // while (idx <= UB) {
3756 // <CodeGen rest of pragma>(LB, UB);
3757 // idx += ST;
3758 // }
3759 //
3760 // For static chunk one schedule generate:
3761 //
3762 // while (IV <= GlobalUB) {
3763 // <CodeGen rest of pragma>(LB, UB);
3764 // LB += ST;
3765 // UB += ST;
3766 // UB = min(UB, GlobalUB);
3767 // IV = LB;
3768 // }
3769 //
Alexey Bataev779a1802019-12-06 12:21:31 -05003770 emitCommonSimdLoop(
3771 *this, S,
3772 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3773 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3774 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3775 },
3776 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
3777 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
3778 CGF.EmitOMPInnerLoop(
3779 S, LoopScope.requiresCleanups(), Cond, IncExpr,
3780 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3781 CodeGenLoop(CGF, S, LoopExit);
3782 },
3783 [&S, StaticChunked](CodeGenFunction &CGF) {
3784 if (StaticChunked) {
3785 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3786 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3787 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3788 CGF.EmitIgnoredExpr(S.getCombinedInit());
3789 }
3790 });
3791 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003792 EmitBlock(LoopExit.getBlock());
3793 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003794 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003795 } else {
3796 // Emit the outer loop, which requests its work chunk [LB..UB] from
3797 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003798 const OMPLoopArguments LoopArguments = {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003799 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3800 IL.getAddress(*this), Chunk};
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003801 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3802 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003803 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003804 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003805 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003806 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003807 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003808 });
3809 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003810 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3811 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3812 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003813 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003814 // Emit post-update of the reduction variables if IsLastIter != 0.
3815 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003816 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003817 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003818 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003819 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003820 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003821 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003822 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003823 EmitOMPLastprivateClauseFinal(
3824 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003825 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003826 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003827 }
3828
3829 // We're now done with the loop, so jump to the continuation block.
3830 if (ContBlock) {
3831 EmitBranch(ContBlock);
3832 EmitBlock(ContBlock, true);
3833 }
3834 }
3835}
3836
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003837void CodeGenFunction::EmitOMPDistributeDirective(
3838 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003839 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003840 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003841 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003842 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003843 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003844}
3845
Alexey Bataev5f600d62015-09-29 03:48:57 +00003846static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3847 const CapturedStmt *S) {
3848 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3849 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3850 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003851 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003852 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003853 return Fn;
3854}
3855
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003856void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003857 if (S.hasClausesOfKind<OMPDependClause>()) {
3858 assert(!S.getAssociatedStmt() &&
3859 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003860 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3861 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003862 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003863 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003864 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003865 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3866 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003867 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003868 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003869 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3870 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003871 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003872 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003873 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003874 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003875 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003876 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003877 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003878 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003879 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003880 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003881}
3882
Alexey Bataevb57056f2015-01-22 06:17:56 +00003883static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003884 QualType SrcType, QualType DestType,
3885 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003886 assert(CGF.hasScalarEvaluationKind(DestType) &&
3887 "DestType must have scalar evaluation kind.");
3888 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003889 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3890 DestType, Loc)
3891 : CGF.EmitComplexToScalarConversion(
3892 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003893}
3894
3895static CodeGenFunction::ComplexPairTy
3896convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003897 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003898 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3899 "DestType must have complex evaluation kind.");
3900 CodeGenFunction::ComplexPairTy ComplexVal;
3901 if (Val.isScalar()) {
3902 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003903 QualType DestElementType =
3904 DestType->castAs<ComplexType>()->getElementType();
3905 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3906 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003907 ComplexVal = CodeGenFunction::ComplexPairTy(
3908 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3909 } else {
3910 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003911 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3912 QualType DestElementType =
3913 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003914 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003915 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003916 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003917 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003918 }
3919 return ComplexVal;
3920}
3921
Alexey Bataev5e018f92015-04-23 06:35:10 +00003922static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3923 LValue LVal, RValue RVal) {
3924 if (LVal.isGlobalReg()) {
3925 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3926 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003927 CGF.EmitAtomicStore(RVal, LVal,
3928 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3929 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003930 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003931 }
3932}
3933
Alexey Bataev8524d152016-01-21 12:35:58 +00003934void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3935 QualType RValTy, SourceLocation Loc) {
3936 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003937 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003938 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3939 *this, RVal, RValTy, LVal.getType(), Loc)),
3940 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003941 break;
3942 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003943 EmitStoreOfComplex(
3944 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003945 /*isInit=*/false);
3946 break;
3947 case TEK_Aggregate:
3948 llvm_unreachable("Must be a scalar or complex.");
3949 }
3950}
3951
Alexey Bataevddf3db92018-04-13 17:31:06 +00003952static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003953 const Expr *X, const Expr *V,
3954 SourceLocation Loc) {
3955 // v = x;
3956 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3957 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3958 LValue XLValue = CGF.EmitLValue(X);
3959 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003960 RValue Res = XLValue.isGlobalReg()
3961 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003962 : CGF.EmitAtomicLoad(
3963 XLValue, Loc,
3964 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3965 : llvm::AtomicOrdering::Monotonic,
3966 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003967 // OpenMP, 2.12.6, atomic Construct
3968 // Any atomic construct with a seq_cst clause forces the atomically
3969 // performed operation to include an implicit flush operation without a
3970 // list.
3971 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003972 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003973 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003974}
3975
Alexey Bataevddf3db92018-04-13 17:31:06 +00003976static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003977 const Expr *X, const Expr *E,
3978 SourceLocation Loc) {
3979 // x = expr;
3980 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003981 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003982 // OpenMP, 2.12.6, atomic Construct
3983 // Any atomic construct with a seq_cst clause forces the atomically
3984 // performed operation to include an implicit flush operation without a
3985 // list.
3986 if (IsSeqCst)
3987 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3988}
3989
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003990static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3991 RValue Update,
3992 BinaryOperatorKind BO,
3993 llvm::AtomicOrdering AO,
3994 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003995 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003996 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003997 // expression is simple and atomic is allowed for the given type for the
3998 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003999 if (BO == BO_Comma || !Update.isScalar() ||
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004000 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
4001 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
4002 (Update.getScalarVal()->getType() !=
4003 X.getAddress(CGF).getElementType())) ||
4004 !X.getAddress(CGF).getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004005 !Context.getTargetInfo().hasBuiltinAtomic(
4006 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00004007 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004008
4009 llvm::AtomicRMWInst::BinOp RMWOp;
4010 switch (BO) {
4011 case BO_Add:
4012 RMWOp = llvm::AtomicRMWInst::Add;
4013 break;
4014 case BO_Sub:
4015 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00004016 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004017 RMWOp = llvm::AtomicRMWInst::Sub;
4018 break;
4019 case BO_And:
4020 RMWOp = llvm::AtomicRMWInst::And;
4021 break;
4022 case BO_Or:
4023 RMWOp = llvm::AtomicRMWInst::Or;
4024 break;
4025 case BO_Xor:
4026 RMWOp = llvm::AtomicRMWInst::Xor;
4027 break;
4028 case BO_LT:
4029 RMWOp = X.getType()->hasSignedIntegerRepresentation()
4030 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
4031 : llvm::AtomicRMWInst::Max)
4032 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
4033 : llvm::AtomicRMWInst::UMax);
4034 break;
4035 case BO_GT:
4036 RMWOp = X.getType()->hasSignedIntegerRepresentation()
4037 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
4038 : llvm::AtomicRMWInst::Min)
4039 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
4040 : llvm::AtomicRMWInst::UMin);
4041 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004042 case BO_Assign:
4043 RMWOp = llvm::AtomicRMWInst::Xchg;
4044 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004045 case BO_Mul:
4046 case BO_Div:
4047 case BO_Rem:
4048 case BO_Shl:
4049 case BO_Shr:
4050 case BO_LAnd:
4051 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00004052 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004053 case BO_PtrMemD:
4054 case BO_PtrMemI:
4055 case BO_LE:
4056 case BO_GE:
4057 case BO_EQ:
4058 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004059 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004060 case BO_AddAssign:
4061 case BO_SubAssign:
4062 case BO_AndAssign:
4063 case BO_OrAssign:
4064 case BO_XorAssign:
4065 case BO_MulAssign:
4066 case BO_DivAssign:
4067 case BO_RemAssign:
4068 case BO_ShlAssign:
4069 case BO_ShrAssign:
4070 case BO_Comma:
4071 llvm_unreachable("Unsupported atomic update operation");
4072 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00004073 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004074 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
4075 UpdateVal = CGF.Builder.CreateIntCast(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004076 IC, X.getAddress(CGF).getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004077 X.getType()->hasSignedIntegerRepresentation());
4078 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00004079 llvm::Value *Res =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004080 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004081 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004082}
4083
Alexey Bataev5e018f92015-04-23 06:35:10 +00004084std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004085 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
4086 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004087 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004088 // Update expressions are allowed to have the following forms:
4089 // x binop= expr; -> xrval + expr;
4090 // x++, ++x -> xrval + 1;
4091 // x--, --x -> xrval - 1;
4092 // x = x binop expr; -> xrval binop expr
4093 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004094 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
4095 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004096 if (X.isGlobalReg()) {
4097 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
4098 // 'xrval'.
4099 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
4100 } else {
4101 // Perform compare-and-swap procedure.
4102 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004103 }
4104 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004105 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004106}
4107
Alexey Bataevddf3db92018-04-13 17:31:06 +00004108static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00004109 const Expr *X, const Expr *E,
4110 const Expr *UE, bool IsXLHSInRHSPart,
4111 SourceLocation Loc) {
4112 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4113 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004114 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004115 // Update expressions are allowed to have the following forms:
4116 // x binop= expr; -> xrval + expr;
4117 // x++, ++x -> xrval + 1;
4118 // x--, --x -> xrval - 1;
4119 // x = x binop expr; -> xrval binop expr
4120 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004121 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00004122 LValue XLValue = CGF.EmitLValue(X);
4123 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004124 llvm::AtomicOrdering AO = IsSeqCst
4125 ? llvm::AtomicOrdering::SequentiallyConsistent
4126 : llvm::AtomicOrdering::Monotonic;
4127 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4128 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4129 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4130 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4131 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
4132 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4133 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4134 return CGF.EmitAnyExpr(UE);
4135 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00004136 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
4137 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4138 // OpenMP, 2.12.6, atomic Construct
4139 // Any atomic construct with a seq_cst clause forces the atomically
4140 // performed operation to include an implicit flush operation without a
4141 // list.
4142 if (IsSeqCst)
4143 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4144}
4145
4146static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004147 QualType SourceType, QualType ResType,
4148 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004149 switch (CGF.getEvaluationKind(ResType)) {
4150 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004151 return RValue::get(
4152 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00004153 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004154 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004155 return RValue::getComplex(Res.first, Res.second);
4156 }
4157 case TEK_Aggregate:
4158 break;
4159 }
4160 llvm_unreachable("Must be a scalar or complex.");
4161}
4162
Alexey Bataevddf3db92018-04-13 17:31:06 +00004163static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004164 bool IsPostfixUpdate, const Expr *V,
4165 const Expr *X, const Expr *E,
4166 const Expr *UE, bool IsXLHSInRHSPart,
4167 SourceLocation Loc) {
4168 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4169 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4170 RValue NewVVal;
4171 LValue VLValue = CGF.EmitLValue(V);
4172 LValue XLValue = CGF.EmitLValue(X);
4173 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004174 llvm::AtomicOrdering AO = IsSeqCst
4175 ? llvm::AtomicOrdering::SequentiallyConsistent
4176 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004177 QualType NewVValType;
4178 if (UE) {
4179 // 'x' is updated with some additional value.
4180 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4181 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004182 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00004183 // Update expressions are allowed to have the following forms:
4184 // x binop= expr; -> xrval + expr;
4185 // x++, ++x -> xrval + 1;
4186 // x--, --x -> xrval - 1;
4187 // x = x binop expr; -> xrval binop expr
4188 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004189 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4190 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4191 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004192 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004193 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004194 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004195 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004196 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4197 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4198 RValue Res = CGF.EmitAnyExpr(UE);
4199 NewVVal = IsPostfixUpdate ? XRValue : Res;
4200 return Res;
4201 };
4202 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4203 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4204 if (Res.first) {
4205 // 'atomicrmw' instruction was generated.
4206 if (IsPostfixUpdate) {
4207 // Use old value from 'atomicrmw'.
4208 NewVVal = Res.second;
4209 } else {
4210 // 'atomicrmw' does not provide new value, so evaluate it using old
4211 // value of 'x'.
4212 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4213 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4214 NewVVal = CGF.EmitAnyExpr(UE);
4215 }
4216 }
4217 } else {
4218 // 'x' is simply rewritten with some 'expr'.
4219 NewVValType = X->getType().getNonReferenceType();
4220 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004221 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004222 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004223 NewVVal = XRValue;
4224 return ExprRValue;
4225 };
4226 // Try to perform atomicrmw xchg, otherwise simple exchange.
4227 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4228 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4229 Loc, Gen);
4230 if (Res.first) {
4231 // 'atomicrmw' instruction was generated.
4232 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4233 }
4234 }
4235 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00004236 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004237 // OpenMP, 2.12.6, atomic Construct
4238 // Any atomic construct with a seq_cst clause forces the atomically
4239 // performed operation to include an implicit flush operation without a
4240 // list.
4241 if (IsSeqCst)
4242 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4243}
4244
Alexey Bataevddf3db92018-04-13 17:31:06 +00004245static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004246 bool IsSeqCst, bool IsPostfixUpdate,
4247 const Expr *X, const Expr *V, const Expr *E,
4248 const Expr *UE, bool IsXLHSInRHSPart,
4249 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004250 switch (Kind) {
4251 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004252 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004253 break;
4254 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004255 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004256 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004257 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004258 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004259 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004260 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004261 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004262 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004263 IsXLHSInRHSPart, Loc);
4264 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004265 case OMPC_if:
4266 case OMPC_final:
4267 case OMPC_num_threads:
4268 case OMPC_private:
4269 case OMPC_firstprivate:
4270 case OMPC_lastprivate:
4271 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004272 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004273 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004274 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004275 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004276 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004277 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004278 case OMPC_collapse:
4279 case OMPC_default:
4280 case OMPC_seq_cst:
4281 case OMPC_shared:
4282 case OMPC_linear:
4283 case OMPC_aligned:
4284 case OMPC_copyin:
4285 case OMPC_copyprivate:
4286 case OMPC_flush:
4287 case OMPC_proc_bind:
4288 case OMPC_schedule:
4289 case OMPC_ordered:
4290 case OMPC_nowait:
4291 case OMPC_untied:
4292 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004293 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004294 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004295 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004296 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004297 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004298 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004299 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004300 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004301 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004302 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004303 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004304 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004305 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004306 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004307 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004308 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004309 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004310 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004311 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004312 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004313 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004314 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004315 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004316 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004317 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004318 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004319 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -05004320 case OMPC_nontemporal:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004321 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4322 }
4323}
4324
4325void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004326 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004327 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004328 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004329 // Find first clause (skip seq_cst clause, if it is first).
4330 if (C->getClauseKind() != OMPC_seq_cst) {
4331 Kind = C->getClauseKind();
4332 break;
4333 }
4334 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004335
Alexey Bataevddf3db92018-04-13 17:31:06 +00004336 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004337 if (const auto *FE = dyn_cast<FullExpr>(CS))
4338 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004339 // Processing for statements under 'atomic capture'.
4340 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004341 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004342 if (const auto *FE = dyn_cast<FullExpr>(C))
4343 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004344 }
4345 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004346
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004347 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4348 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004349 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004350 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004351 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004352 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004353 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004354 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004355 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004356}
4357
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004358static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4359 const OMPExecutableDirective &S,
4360 const RegionCodeGenTy &CodeGen) {
4361 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4362 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004363
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004364 // On device emit this construct as inlined code.
4365 if (CGM.getLangOpts().OpenMPIsDevice) {
4366 OMPLexicalScope Scope(CGF, S, OMPD_target);
4367 CGM.getOpenMPRuntime().emitInlinedDirective(
4368 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004369 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004370 });
4371 return;
4372 }
4373
Samuel Antaoee8fb302016-01-06 13:42:12 +00004374 llvm::Function *Fn = nullptr;
4375 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004376
Samuel Antaobed3c462015-10-02 16:14:20 +00004377 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004378 // Check for the at most one if clause associated with the target region.
4379 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4380 if (C->getNameModifier() == OMPD_unknown ||
4381 C->getNameModifier() == OMPD_target) {
4382 IfCond = C->getCondition();
4383 break;
4384 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004385 }
4386
4387 // Check if we have any device clause associated with the directive.
4388 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004389 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004390 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004391
Samuel Antaoee8fb302016-01-06 13:42:12 +00004392 // Check if we have an if clause whose conditional always evaluates to false
4393 // or if we do not have any targets specified. If so the target region is not
4394 // an offload entry point.
4395 bool IsOffloadEntry = true;
4396 if (IfCond) {
4397 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004398 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004399 IsOffloadEntry = false;
4400 }
4401 if (CGM.getLangOpts().OMPTargetTriples.empty())
4402 IsOffloadEntry = false;
4403
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004404 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004405 StringRef ParentName;
4406 // In case we have Ctors/Dtors we use the complete type variant to produce
4407 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004408 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004409 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004410 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004411 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4412 else
4413 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004414 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004415
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004416 // Emit target region as a standalone region.
4417 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4418 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004419 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004420 auto &&SizeEmitter =
4421 [IsOffloadEntry](CodeGenFunction &CGF,
4422 const OMPLoopDirective &D) -> llvm::Value * {
4423 if (IsOffloadEntry) {
4424 OMPLoopScope(CGF, D);
4425 // Emit calculation of the iterations count.
4426 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4427 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4428 /*isSigned=*/false);
4429 return NumIterations;
4430 }
4431 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004432 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004433 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4434 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004435}
4436
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004437static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4438 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004439 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004440 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4441 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4442 CGF.EmitOMPPrivateClause(S, PrivateScope);
4443 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004444 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4445 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004446
Alexey Bataev475a7442018-01-12 19:39:11 +00004447 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004448}
4449
4450void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4451 StringRef ParentName,
4452 const OMPTargetDirective &S) {
4453 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4454 emitTargetRegion(CGF, S, Action);
4455 };
4456 llvm::Function *Fn;
4457 llvm::Constant *Addr;
4458 // Emit target region as a standalone region.
4459 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4460 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4461 assert(Fn && Addr && "Target device function emission failed.");
4462}
4463
4464void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4465 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4466 emitTargetRegion(CGF, S, Action);
4467 };
4468 emitCommonOMPTargetDirective(*this, S, CodeGen);
4469}
4470
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004471static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4472 const OMPExecutableDirective &S,
4473 OpenMPDirectiveKind InnermostKind,
4474 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004475 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004476 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004477 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4478 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004479
Alexey Bataevddf3db92018-04-13 17:31:06 +00004480 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4481 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004482 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004483 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4484 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004485
Carlo Bertollic6872252016-04-04 15:55:02 +00004486 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004487 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004488 }
4489
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004490 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004491 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4492 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004493 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004494 CapturedVars);
4495}
4496
4497void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004498 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004499 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004500 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004501 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004502 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4503 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004504 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004505 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004506 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004507 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004508 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004509 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004510 emitPostUpdateForReductionClause(*this, S,
4511 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004512}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004513
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004514static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4515 const OMPTargetTeamsDirective &S) {
4516 auto *CS = S.getCapturedStmt(OMPD_teams);
4517 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004518 // Emit teams region as a standalone region.
4519 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004520 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004521 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4522 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4523 CGF.EmitOMPPrivateClause(S, PrivateScope);
4524 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4525 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004526 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4527 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004528 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004529 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004530 };
4531 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004532 emitPostUpdateForReductionClause(CGF, S,
4533 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004534}
4535
4536void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4537 CodeGenModule &CGM, StringRef ParentName,
4538 const OMPTargetTeamsDirective &S) {
4539 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4540 emitTargetTeamsRegion(CGF, Action, S);
4541 };
4542 llvm::Function *Fn;
4543 llvm::Constant *Addr;
4544 // Emit target region as a standalone region.
4545 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4546 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4547 assert(Fn && Addr && "Target device function emission failed.");
4548}
4549
4550void CodeGenFunction::EmitOMPTargetTeamsDirective(
4551 const OMPTargetTeamsDirective &S) {
4552 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4553 emitTargetTeamsRegion(CGF, Action, S);
4554 };
4555 emitCommonOMPTargetDirective(*this, S, CodeGen);
4556}
4557
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004558static void
4559emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4560 const OMPTargetTeamsDistributeDirective &S) {
4561 Action.Enter(CGF);
4562 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4563 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4564 };
4565
4566 // Emit teams region as a standalone region.
4567 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004568 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004569 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004570 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4571 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4572 (void)PrivateScope.Privatize();
4573 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4574 CodeGenDistribute);
4575 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4576 };
4577 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4578 emitPostUpdateForReductionClause(CGF, S,
4579 [](CodeGenFunction &) { return nullptr; });
4580}
4581
4582void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4583 CodeGenModule &CGM, StringRef ParentName,
4584 const OMPTargetTeamsDistributeDirective &S) {
4585 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4586 emitTargetTeamsDistributeRegion(CGF, Action, S);
4587 };
4588 llvm::Function *Fn;
4589 llvm::Constant *Addr;
4590 // Emit target region as a standalone region.
4591 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4592 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4593 assert(Fn && Addr && "Target device function emission failed.");
4594}
4595
4596void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4597 const OMPTargetTeamsDistributeDirective &S) {
4598 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4599 emitTargetTeamsDistributeRegion(CGF, Action, S);
4600 };
4601 emitCommonOMPTargetDirective(*this, S, CodeGen);
4602}
4603
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004604static void emitTargetTeamsDistributeSimdRegion(
4605 CodeGenFunction &CGF, PrePostActionTy &Action,
4606 const OMPTargetTeamsDistributeSimdDirective &S) {
4607 Action.Enter(CGF);
4608 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4609 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4610 };
4611
4612 // Emit teams region as a standalone region.
4613 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004614 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004615 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004616 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4617 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4618 (void)PrivateScope.Privatize();
4619 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4620 CodeGenDistribute);
4621 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4622 };
4623 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4624 emitPostUpdateForReductionClause(CGF, S,
4625 [](CodeGenFunction &) { return nullptr; });
4626}
4627
4628void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4629 CodeGenModule &CGM, StringRef ParentName,
4630 const OMPTargetTeamsDistributeSimdDirective &S) {
4631 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4632 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4633 };
4634 llvm::Function *Fn;
4635 llvm::Constant *Addr;
4636 // Emit target region as a standalone region.
4637 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4638 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4639 assert(Fn && Addr && "Target device function emission failed.");
4640}
4641
4642void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4643 const OMPTargetTeamsDistributeSimdDirective &S) {
4644 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4645 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4646 };
4647 emitCommonOMPTargetDirective(*this, S, CodeGen);
4648}
4649
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004650void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4651 const OMPTeamsDistributeDirective &S) {
4652
4653 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4654 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4655 };
4656
4657 // Emit teams region as a standalone region.
4658 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004659 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004660 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004661 OMPPrivateScope PrivateScope(CGF);
4662 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4663 (void)PrivateScope.Privatize();
4664 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4665 CodeGenDistribute);
4666 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4667 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004668 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004669 emitPostUpdateForReductionClause(*this, S,
4670 [](CodeGenFunction &) { return nullptr; });
4671}
4672
Alexey Bataev999277a2017-12-06 14:31:09 +00004673void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4674 const OMPTeamsDistributeSimdDirective &S) {
4675 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4676 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4677 };
4678
4679 // Emit teams region as a standalone region.
4680 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004681 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004682 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004683 OMPPrivateScope PrivateScope(CGF);
4684 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4685 (void)PrivateScope.Privatize();
4686 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4687 CodeGenDistribute);
4688 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4689 };
4690 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4691 emitPostUpdateForReductionClause(*this, S,
4692 [](CodeGenFunction &) { return nullptr; });
4693}
4694
Carlo Bertolli62fae152017-11-20 20:46:39 +00004695void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4696 const OMPTeamsDistributeParallelForDirective &S) {
4697 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4698 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4699 S.getDistInc());
4700 };
4701
4702 // Emit teams region as a standalone region.
4703 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004704 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004705 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004706 OMPPrivateScope PrivateScope(CGF);
4707 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4708 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004709 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4710 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004711 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4712 };
4713 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4714 emitPostUpdateForReductionClause(*this, S,
4715 [](CodeGenFunction &) { return nullptr; });
4716}
4717
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004718void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4719 const OMPTeamsDistributeParallelForSimdDirective &S) {
4720 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4721 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4722 S.getDistInc());
4723 };
4724
4725 // Emit teams region as a standalone region.
4726 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004727 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004728 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004729 OMPPrivateScope PrivateScope(CGF);
4730 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4731 (void)PrivateScope.Privatize();
4732 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4733 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4734 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4735 };
Alexey Bataev0b978942019-12-11 15:26:38 -05004736 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
4737 CodeGen);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004738 emitPostUpdateForReductionClause(*this, S,
4739 [](CodeGenFunction &) { return nullptr; });
4740}
4741
Carlo Bertolli52978c32018-01-03 21:12:44 +00004742static void emitTargetTeamsDistributeParallelForRegion(
4743 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4744 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004745 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004746 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4747 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4748 S.getDistInc());
4749 };
4750
4751 // Emit teams region as a standalone region.
4752 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004753 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004754 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004755 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4756 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4757 (void)PrivateScope.Privatize();
4758 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4759 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4760 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4761 };
4762
4763 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4764 CodeGenTeams);
4765 emitPostUpdateForReductionClause(CGF, S,
4766 [](CodeGenFunction &) { return nullptr; });
4767}
4768
4769void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4770 CodeGenModule &CGM, StringRef ParentName,
4771 const OMPTargetTeamsDistributeParallelForDirective &S) {
4772 // Emit SPMD target teams distribute parallel for region as a standalone
4773 // region.
4774 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4775 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4776 };
4777 llvm::Function *Fn;
4778 llvm::Constant *Addr;
4779 // Emit target region as a standalone region.
4780 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4781 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4782 assert(Fn && Addr && "Target device function emission failed.");
4783}
4784
4785void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4786 const OMPTargetTeamsDistributeParallelForDirective &S) {
4787 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4788 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4789 };
4790 emitCommonOMPTargetDirective(*this, S, CodeGen);
4791}
4792
Alexey Bataev647dd842018-01-15 20:59:40 +00004793static void emitTargetTeamsDistributeParallelForSimdRegion(
4794 CodeGenFunction &CGF,
4795 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4796 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004797 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004798 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4799 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4800 S.getDistInc());
4801 };
4802
4803 // Emit teams region as a standalone region.
4804 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004805 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004806 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004807 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4808 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4809 (void)PrivateScope.Privatize();
4810 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4811 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4812 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4813 };
4814
4815 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4816 CodeGenTeams);
4817 emitPostUpdateForReductionClause(CGF, S,
4818 [](CodeGenFunction &) { return nullptr; });
4819}
4820
4821void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4822 CodeGenModule &CGM, StringRef ParentName,
4823 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4824 // Emit SPMD target teams distribute parallel for simd region as a standalone
4825 // region.
4826 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4827 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4828 };
4829 llvm::Function *Fn;
4830 llvm::Constant *Addr;
4831 // Emit target region as a standalone region.
4832 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4833 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4834 assert(Fn && Addr && "Target device function emission failed.");
4835}
4836
4837void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4838 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4839 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4840 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4841 };
4842 emitCommonOMPTargetDirective(*this, S, CodeGen);
4843}
4844
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004845void CodeGenFunction::EmitOMPCancellationPointDirective(
4846 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004847 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004848 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004849}
4850
Alexey Bataev80909872015-07-02 11:25:17 +00004851void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004852 const Expr *IfCond = nullptr;
4853 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4854 if (C->getNameModifier() == OMPD_unknown ||
4855 C->getNameModifier() == OMPD_cancel) {
4856 IfCond = C->getCondition();
4857 break;
4858 }
4859 }
Johannes Doerfert10fedd92019-12-26 11:23:38 -06004860 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
4861 // TODO: This check is necessary as we only generate `omp parallel` through
4862 // the OpenMPIRBuilder for now.
4863 if (S.getCancelRegion() == OMPD_parallel) {
4864 llvm::Value *IfCondition = nullptr;
4865 if (IfCond)
4866 IfCondition = EmitScalarExpr(IfCond,
4867 /*IgnoreResultAssign=*/true);
4868 return Builder.restoreIP(
4869 OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion()));
4870 }
4871 }
4872
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004873 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004874 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004875}
4876
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004877CodeGenFunction::JumpDest
4878CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004879 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4880 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004881 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004882 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004883 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4884 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004885 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004886 Kind == OMPD_teams_distribute_parallel_for ||
4887 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004888 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004889}
Michael Wong65f367f2015-07-21 13:44:28 +00004890
Samuel Antaocc10b852016-07-28 14:23:26 +00004891void CodeGenFunction::EmitOMPUseDevicePtrClause(
4892 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4893 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4894 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4895 auto OrigVarIt = C.varlist_begin();
4896 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004897 for (const Expr *PvtVarIt : C.private_copies()) {
4898 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4899 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4900 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004901
4902 // In order to identify the right initializer we need to match the
4903 // declaration used by the mapping logic. In some cases we may get
4904 // OMPCapturedExprDecl that refers to the original declaration.
4905 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004906 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004907 // OMPCapturedExprDecl are used to privative fields of the current
4908 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004909 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004910 assert(isa<CXXThisExpr>(ME->getBase()) &&
4911 "Base should be the current struct!");
4912 MatchingVD = ME->getMemberDecl();
4913 }
4914
4915 // If we don't have information about the current list item, move on to
4916 // the next one.
4917 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4918 if (InitAddrIt == CaptureDeviceAddrMap.end())
4919 continue;
4920
Alexey Bataevddf3db92018-04-13 17:31:06 +00004921 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4922 InitAddrIt, InitVD,
4923 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004924 // Initialize the temporary initialization variable with the address we
4925 // get from the runtime library. We have to cast the source address
4926 // because it is always a void *. References are materialized in the
4927 // privatization scope, so the initialization here disregards the fact
4928 // the original variable is a reference.
4929 QualType AddrQTy =
4930 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4931 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4932 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4933 setAddrOfLocalVar(InitVD, InitAddr);
4934
4935 // Emit private declaration, it will be initialized by the value we
4936 // declaration we just added to the local declarations map.
4937 EmitDecl(*PvtVD);
4938
4939 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004940 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004941 LocalDeclMap.erase(InitVD);
4942
4943 // Return the address of the private variable.
4944 return GetAddrOfLocalVar(PvtVD);
4945 });
4946 assert(IsRegistered && "firstprivate var already registered as private");
4947 // Silence the warning about unused variable.
4948 (void)IsRegistered;
4949
4950 ++OrigVarIt;
4951 ++InitIt;
4952 }
4953}
4954
Michael Wong65f367f2015-07-21 13:44:28 +00004955// Generate the instructions for '#pragma omp target data' directive.
4956void CodeGenFunction::EmitOMPTargetDataDirective(
4957 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004958 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4959
4960 // Create a pre/post action to signal the privatization of the device pointer.
4961 // This action can be replaced by the OpenMP runtime code generation to
4962 // deactivate privatization.
4963 bool PrivatizeDevicePointers = false;
4964 class DevicePointerPrivActionTy : public PrePostActionTy {
4965 bool &PrivatizeDevicePointers;
4966
4967 public:
4968 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4969 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4970 void Enter(CodeGenFunction &CGF) override {
4971 PrivatizeDevicePointers = true;
4972 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004973 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004974 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4975
4976 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004977 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004978 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004979 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004980 };
4981
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004982 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004983 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4984 &InnermostCodeGen](CodeGenFunction &CGF,
4985 PrePostActionTy &Action) {
4986 RegionCodeGenTy RCG(InnermostCodeGen);
4987 PrivatizeDevicePointers = false;
4988
4989 // Call the pre-action to change the status of PrivatizeDevicePointers if
4990 // needed.
4991 Action.Enter(CGF);
4992
4993 if (PrivatizeDevicePointers) {
4994 OMPPrivateScope PrivateScope(CGF);
4995 // Emit all instances of the use_device_ptr clause.
4996 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4997 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4998 Info.CaptureDeviceAddrMap);
4999 (void)PrivateScope.Privatize();
5000 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005001 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00005002 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005003 }
Samuel Antaocc10b852016-07-28 14:23:26 +00005004 };
5005
5006 // Forward the provided action to the privatization codegen.
5007 RegionCodeGenTy PrivRCG(PrivCodeGen);
5008 PrivRCG.setAction(Action);
5009
5010 // Notwithstanding the body of the region is emitted as inlined directive,
5011 // we don't use an inline scope as changes in the references inside the
5012 // region are expected to be visible outside, so we do not privative them.
5013 OMPLexicalScope Scope(CGF, S);
5014 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
5015 PrivRCG);
5016 };
5017
5018 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00005019
5020 // If we don't have target devices, don't bother emitting the data mapping
5021 // code.
5022 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005023 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00005024 return;
5025 }
5026
5027 // Check if we have any if clause associated with the directive.
5028 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005029 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00005030 IfCond = C->getCondition();
5031
5032 // Check if we have any device clause associated with the directive.
5033 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005034 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00005035 Device = C->getDevice();
5036
Samuel Antaocc10b852016-07-28 14:23:26 +00005037 // Set the action to signal privatization of device pointers.
5038 RCG.setAction(PrivAction);
5039
5040 // Emit region code.
5041 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
5042 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00005043}
Alexey Bataev49f6e782015-12-01 04:18:41 +00005044
Samuel Antaodf67fc42016-01-19 19:15:56 +00005045void CodeGenFunction::EmitOMPTargetEnterDataDirective(
5046 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005047 // If we don't have target devices, don't bother emitting the data mapping
5048 // code.
5049 if (CGM.getLangOpts().OMPTargetTriples.empty())
5050 return;
5051
5052 // Check if we have any if clause associated with the directive.
5053 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005054 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005055 IfCond = C->getCondition();
5056
5057 // Check if we have any device clause associated with the directive.
5058 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005059 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005060 Device = C->getDevice();
5061
Alexey Bataev475a7442018-01-12 19:39:11 +00005062 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005063 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005064}
5065
Samuel Antao72590762016-01-19 20:04:50 +00005066void CodeGenFunction::EmitOMPTargetExitDataDirective(
5067 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00005068 // If we don't have target devices, don't bother emitting the data mapping
5069 // code.
5070 if (CGM.getLangOpts().OMPTargetTriples.empty())
5071 return;
5072
5073 // Check if we have any if clause associated with the directive.
5074 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005075 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00005076 IfCond = C->getCondition();
5077
5078 // Check if we have any device clause associated with the directive.
5079 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005080 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00005081 Device = C->getDevice();
5082
Alexey Bataev475a7442018-01-12 19:39:11 +00005083 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005084 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00005085}
5086
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005087static void emitTargetParallelRegion(CodeGenFunction &CGF,
5088 const OMPTargetParallelDirective &S,
5089 PrePostActionTy &Action) {
5090 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00005091 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005092 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00005093 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005094 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005095 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5096 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5097 CGF.EmitOMPPrivateClause(S, PrivateScope);
5098 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5099 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00005100 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5101 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005102 // TODO: Add support for clauses.
5103 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005104 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005105 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00005106 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
5107 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005108 emitPostUpdateForReductionClause(CGF, S,
5109 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005110}
5111
5112void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
5113 CodeGenModule &CGM, StringRef ParentName,
5114 const OMPTargetParallelDirective &S) {
5115 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5116 emitTargetParallelRegion(CGF, S, Action);
5117 };
5118 llvm::Function *Fn;
5119 llvm::Constant *Addr;
5120 // Emit target region as a standalone region.
5121 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5122 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5123 assert(Fn && Addr && "Target device function emission failed.");
5124}
5125
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005126void CodeGenFunction::EmitOMPTargetParallelDirective(
5127 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00005128 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5129 emitTargetParallelRegion(CGF, S, Action);
5130 };
5131 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005132}
5133
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005134static void emitTargetParallelForRegion(CodeGenFunction &CGF,
5135 const OMPTargetParallelForDirective &S,
5136 PrePostActionTy &Action) {
5137 Action.Enter(CGF);
5138 // Emit directive as a combined directive that consists of two implicit
5139 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005140 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5141 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00005142 CodeGenFunction::OMPCancelStackRAII CancelRegion(
5143 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005144 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5145 emitDispatchForLoopBounds);
5146 };
5147 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
5148 emitEmptyBoundParameters);
5149}
5150
5151void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
5152 CodeGenModule &CGM, StringRef ParentName,
5153 const OMPTargetParallelForDirective &S) {
5154 // Emit SPMD target parallel for region as a standalone region.
5155 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5156 emitTargetParallelForRegion(CGF, S, Action);
5157 };
5158 llvm::Function *Fn;
5159 llvm::Constant *Addr;
5160 // Emit target region as a standalone region.
5161 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5162 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5163 assert(Fn && Addr && "Target device function emission failed.");
5164}
5165
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005166void CodeGenFunction::EmitOMPTargetParallelForDirective(
5167 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00005168 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5169 emitTargetParallelForRegion(CGF, S, Action);
5170 };
5171 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005172}
5173
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005174static void
5175emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5176 const OMPTargetParallelForSimdDirective &S,
5177 PrePostActionTy &Action) {
5178 Action.Enter(CGF);
5179 // Emit directive as a combined directive that consists of two implicit
5180 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005181 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5182 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005183 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5184 emitDispatchForLoopBounds);
5185 };
5186 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5187 emitEmptyBoundParameters);
5188}
5189
5190void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5191 CodeGenModule &CGM, StringRef ParentName,
5192 const OMPTargetParallelForSimdDirective &S) {
5193 // Emit SPMD target parallel for region as a standalone region.
5194 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5195 emitTargetParallelForSimdRegion(CGF, S, Action);
5196 };
5197 llvm::Function *Fn;
5198 llvm::Constant *Addr;
5199 // Emit target region as a standalone region.
5200 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5201 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5202 assert(Fn && Addr && "Target device function emission failed.");
5203}
5204
5205void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5206 const OMPTargetParallelForSimdDirective &S) {
5207 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5208 emitTargetParallelForSimdRegion(CGF, S, Action);
5209 };
5210 emitCommonOMPTargetDirective(*this, S, CodeGen);
5211}
5212
Alexey Bataev7292c292016-04-25 12:22:29 +00005213/// Emit a helper variable and return corresponding lvalue.
5214static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5215 const ImplicitParamDecl *PVD,
5216 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005217 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5218 Privates.addPrivate(VDecl,
5219 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00005220}
5221
5222void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5223 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5224 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00005225 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005226 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5227 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005228 const Expr *IfCond = nullptr;
5229 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5230 if (C->getNameModifier() == OMPD_unknown ||
5231 C->getNameModifier() == OMPD_taskloop) {
5232 IfCond = C->getCondition();
5233 break;
5234 }
5235 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005236
5237 OMPTaskDataTy Data;
5238 // Check if taskloop must be emitted without taskgroup.
5239 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00005240 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005241 Data.Tied = true;
5242 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005243 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5244 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005245 Data.Schedule.setInt(/*IntVal=*/false);
5246 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005247 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5248 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005249 Data.Schedule.setInt(/*IntVal=*/true);
5250 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005251 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005252
5253 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5254 // if (PreCond) {
5255 // for (IV in 0..LastIteration) BODY;
5256 // <Final counter/linear vars updates>;
5257 // }
5258 //
5259
5260 // Emit: if (PreCond) - begin.
5261 // If the condition constant folds and can be elided, avoid emitting the
5262 // whole loop.
5263 bool CondConstant;
5264 llvm::BasicBlock *ContBlock = nullptr;
5265 OMPLoopScope PreInitScope(CGF, S);
5266 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5267 if (!CondConstant)
5268 return;
5269 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005270 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005271 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5272 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5273 CGF.getProfileCount(&S));
5274 CGF.EmitBlock(ThenBlock);
5275 CGF.incrementProfileCounter(&S);
5276 }
5277
Alexey Bataev61205822019-12-04 09:50:21 -05005278 (void)CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005279
Alexey Bataev7292c292016-04-25 12:22:29 +00005280 OMPPrivateScope LoopScope(CGF);
5281 // Emit helper vars inits.
5282 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5283 auto *I = CS->getCapturedDecl()->param_begin();
5284 auto *LBP = std::next(I, LowerBound);
5285 auto *UBP = std::next(I, UpperBound);
5286 auto *STP = std::next(I, Stride);
5287 auto *LIP = std::next(I, LastIter);
5288 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5289 LoopScope);
5290 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5291 LoopScope);
5292 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5293 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5294 LoopScope);
5295 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005296 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005297 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005298 (void)LoopScope.Privatize();
5299 // Emit the loop iteration variable.
5300 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005301 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005302 CGF.EmitVarDecl(*IVDecl);
5303 CGF.EmitIgnoredExpr(S.getInit());
5304
5305 // Emit the iterations count variable.
5306 // If it is not a variable, Sema decided to calculate iterations count on
5307 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005308 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005309 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5310 // Emit calculation of the iterations count.
5311 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5312 }
5313
Alexey Bataev61205822019-12-04 09:50:21 -05005314 {
5315 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
5316 emitCommonSimdLoop(
5317 CGF, S,
5318 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5319 if (isOpenMPSimdDirective(S.getDirectiveKind()))
5320 CGF.EmitOMPSimdInit(S);
5321 },
5322 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
5323 CGF.EmitOMPInnerLoop(
5324 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
5325 [&S](CodeGenFunction &CGF) {
5326 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
5327 CGF.EmitStopPoint(&S);
5328 },
5329 [](CodeGenFunction &) {});
5330 });
5331 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005332 // Emit: if (PreCond) - end.
5333 if (ContBlock) {
5334 CGF.EmitBranch(ContBlock);
5335 CGF.EmitBlock(ContBlock, true);
5336 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005337 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5338 if (HasLastprivateClause) {
5339 CGF.EmitOMPLastprivateClauseFinal(
5340 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5341 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5342 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005343 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005344 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04005345 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5346 return CGF.Builder.CreateIsNotNull(
5347 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5348 (*LIP)->getType(), S.getBeginLoc()));
5349 });
Alexey Bataev7292c292016-04-25 12:22:29 +00005350 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005351 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005352 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005353 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005354 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5355 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005356 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005357 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005358 OutlinedFn, SharedsTy,
5359 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005360 };
5361 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5362 CodeGen);
5363 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005364 if (Data.Nogroup) {
5365 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5366 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005367 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5368 *this,
5369 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5370 PrePostActionTy &Action) {
5371 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005372 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5373 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005374 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005375 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005376 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005377}
5378
Alexey Bataev49f6e782015-12-01 04:18:41 +00005379void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005380 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005381}
5382
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005383void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5384 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev61205822019-12-04 09:50:21 -05005385 OMPLexicalScope Scope(*this, S);
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005386 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005387}
Samuel Antao686c70c2016-05-26 17:30:50 +00005388
Alexey Bataev60e51c42019-10-10 20:13:02 +00005389void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5390 const OMPMasterTaskLoopDirective &S) {
5391 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5392 Action.Enter(CGF);
5393 EmitOMPTaskLoopBasedDirective(S);
5394 };
5395 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5396 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5397}
5398
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005399void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5400 const OMPMasterTaskLoopSimdDirective &S) {
5401 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5402 Action.Enter(CGF);
5403 EmitOMPTaskLoopBasedDirective(S);
5404 };
Alexey Bataev61205822019-12-04 09:50:21 -05005405 OMPLexicalScope Scope(*this, S);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005406 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5407}
5408
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005409void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5410 const OMPParallelMasterTaskLoopDirective &S) {
5411 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5412 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5413 PrePostActionTy &Action) {
5414 Action.Enter(CGF);
5415 CGF.EmitOMPTaskLoopBasedDirective(S);
5416 };
5417 OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5418 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5419 S.getBeginLoc());
5420 };
5421 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5422 emitEmptyBoundParameters);
5423}
5424
Alexey Bataev14a388f2019-10-25 10:27:13 -04005425void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5426 const OMPParallelMasterTaskLoopSimdDirective &S) {
5427 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5428 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5429 PrePostActionTy &Action) {
5430 Action.Enter(CGF);
5431 CGF.EmitOMPTaskLoopBasedDirective(S);
5432 };
5433 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5434 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5435 S.getBeginLoc());
5436 };
5437 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5438 emitEmptyBoundParameters);
5439}
5440
Samuel Antao686c70c2016-05-26 17:30:50 +00005441// Generate the instructions for '#pragma omp target update' directive.
5442void CodeGenFunction::EmitOMPTargetUpdateDirective(
5443 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005444 // If we don't have target devices, don't bother emitting the data mapping
5445 // code.
5446 if (CGM.getLangOpts().OMPTargetTriples.empty())
5447 return;
5448
5449 // Check if we have any if clause associated with the directive.
5450 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005451 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005452 IfCond = C->getCondition();
5453
5454 // Check if we have any device clause associated with the directive.
5455 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005456 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005457 Device = C->getDevice();
5458
Alexey Bataev475a7442018-01-12 19:39:11 +00005459 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005460 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005461}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005462
5463void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5464 const OMPExecutableDirective &D) {
5465 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5466 return;
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08005467 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005468 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5469 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5470 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005471 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005472 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005473 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005474 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5475 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5476 LValue GlobLVal = CGF.EmitLValue(E);
5477 LoopGlobals.addPrivate(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08005478 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005479 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005480 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005481 // Emit only those that were not explicitly referenced in clauses.
5482 if (!CGF.LocalDeclMap.count(VD))
5483 CGF.EmitVarDecl(*VD);
5484 }
5485 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005486 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5487 if (!C->getNumForLoops())
5488 continue;
5489 for (unsigned I = LD->getCollapsedNumber(),
5490 E = C->getLoopNumIterations().size();
5491 I < E; ++I) {
5492 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005493 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005494 // Emit only those that were not explicitly referenced in clauses.
5495 if (!CGF.LocalDeclMap.count(VD))
5496 CGF.EmitVarDecl(*VD);
5497 }
5498 }
5499 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005500 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005501 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005502 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005503 }
5504 };
5505 OMPSimdLexicalScope Scope(*this, D);
5506 CGM.getOpenMPRuntime().emitInlinedDirective(
5507 *this,
5508 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5509 : D.getDirectiveKind(),
5510 CodeGen);
5511}