blob: 01194e3a60fa189b6c70679b23cc0146fc2e1906 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev9959db52014-05-06 10:08:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit OpenMP nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Alexey Bataev3392d762016-02-16 11:18:12 +000013#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000014#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021using namespace clang;
22using namespace CodeGen;
23
Alexey Bataev3392d762016-02-16 11:18:12 +000024namespace {
25/// Lexical scope for OpenMP executable constructs, that handles correct codegen
26/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000027class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000028 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
29 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000030 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
31 if (const auto *PreInit =
32 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000033 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000034 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000035 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000036 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000037 CodeGenFunction::AutoVarEmission Emission =
38 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
39 CGF.EmitAutoVarCleanups(Emission);
40 }
41 }
Alexey Bataev3392d762016-02-16 11:18:12 +000042 }
43 }
44 }
45 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000046 CodeGenFunction::OMPPrivateScope InlinedShareds;
47
48 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
49 return CGF.LambdaCaptureFields.lookup(VD) ||
50 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
51 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
52 }
Alexey Bataev3392d762016-02-16 11:18:12 +000053
Alexey Bataev3392d762016-02-16 11:18:12 +000054public:
Alexey Bataev475a7442018-01-12 19:39:11 +000055 OMPLexicalScope(
56 CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
58 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000059 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
60 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000061 if (EmitPreInitStmt)
62 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000063 if (!CapturedRegion.hasValue())
64 return;
65 assert(S.hasAssociatedStmt() &&
66 "Expected associated statement for inlined directive.");
67 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000068 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000069 if (C.capturesVariable() || C.capturesVariableByCopy()) {
70 auto *VD = C.getCapturedVar();
71 assert(VD == VD->getCanonicalDecl() &&
72 "Canonical decl must be captured.");
73 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000074 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000075 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
76 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000077 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000078 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
79 return CGF.EmitLValue(&DRE).getAddress();
80 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000081 }
82 }
Alexey Bataev475a7442018-01-12 19:39:11 +000083 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +000099 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
100 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000101};
102
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000103/// Lexical scope for OpenMP teams construct, that handles correct codegen
104/// for captured expressions.
105class OMPTeamsScope final : public OMPLexicalScope {
106 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
107 OpenMPDirectiveKind Kind = S.getDirectiveKind();
108 return !isOpenMPTargetExecutionDirective(Kind) &&
109 isOpenMPTeamsDirective(Kind);
110 }
111
112public:
113 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000114 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
115 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000122 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000123 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000125 (void)PreCondVars.setVarAddr(
126 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000127 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000128 (void)PreCondVars.apply(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000129 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000130 for (const auto *I : PreInits->decls())
131 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000132 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000133 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000134 }
135
136public:
137 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
138 : CodeGenFunction::RunCleanupsScope(CGF) {
139 emitPreInitStmt(CGF, S);
140 }
141};
142
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000143class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
144 CodeGenFunction::OMPPrivateScope InlinedShareds;
145
146 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
147 return CGF.LambdaCaptureFields.lookup(VD) ||
148 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
149 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
150 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
151 }
152
153public:
154 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
155 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
156 InlinedShareds(CGF) {
157 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000158 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
159 if (const auto *PreInit =
160 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000161 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000162 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000163 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000164 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000165 CodeGenFunction::AutoVarEmission Emission =
166 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
167 CGF.EmitAutoVarCleanups(Emission);
168 }
169 }
170 }
171 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
172 for (const Expr *E : UDP->varlists()) {
173 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
174 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
175 CGF.EmitVarDecl(*OED);
176 }
177 }
178 }
179 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
180 CGF.EmitOMPPrivateClause(S, InlinedShareds);
181 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
182 if (const Expr *E = TG->getReductionRef())
183 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
184 }
185 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
186 while (CS) {
187 for (auto &C : CS->captures()) {
188 if (C.capturesVariable() || C.capturesVariableByCopy()) {
189 auto *VD = C.getCapturedVar();
190 assert(VD == VD->getCanonicalDecl() &&
191 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000192 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000193 isCapturedVar(CGF, VD) ||
194 (CGF.CapturedStmtInfo &&
195 InlinedShareds.isGlobalVarCaptured(VD)),
196 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000197 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000198 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
199 return CGF.EmitLValue(&DRE).getAddress();
200 });
201 }
202 }
203 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
204 }
205 (void)InlinedShareds.Privatize();
206 }
207};
208
Alexey Bataev3392d762016-02-16 11:18:12 +0000209} // namespace
210
Alexey Bataevf8365372017-11-17 17:57:25 +0000211static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
212 const OMPExecutableDirective &S,
213 const RegionCodeGenTy &CodeGen);
214
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000215LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000216 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
217 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000218 OrigVD = OrigVD->getCanonicalDecl();
219 bool IsCaptured =
220 LambdaCaptureFields.lookup(OrigVD) ||
221 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
222 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000223 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000224 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
225 return EmitLValue(&DRE);
226 }
227 }
228 return EmitLValue(E);
229}
230
Alexey Bataev1189bd02016-01-26 12:20:39 +0000231llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000232 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233 llvm::Value *Size = nullptr;
234 auto SizeInChars = C.getTypeSizeInChars(Ty);
235 if (SizeInChars.isZero()) {
236 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000237 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
238 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000239 Ty = VlaSize.Type;
240 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
241 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000242 }
243 SizeInChars = C.getTypeSizeInChars(Ty);
244 if (SizeInChars.isZero())
245 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000246 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
247 }
248 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000249}
250
Alexey Bataev2377fe92015-09-10 08:12:02 +0000251void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000252 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000253 const RecordDecl *RD = S.getCapturedRecordDecl();
254 auto CurField = RD->field_begin();
255 auto CurCap = S.captures().begin();
256 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
257 E = S.capture_init_end();
258 I != E; ++I, ++CurField, ++CurCap) {
259 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000260 const VariableArrayType *VAT = CurField->getCapturedVLAType();
261 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000262 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000263 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000264 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000265 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000266 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000267
268 // If the field is not a pointer, we need to save the actual value
269 // and load it as a void pointer.
270 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000271 ASTContext &Ctx = getContext();
272 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000273 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000274 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000275 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
276
Alexey Bataevddf3db92018-04-13 17:31:06 +0000277 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000278 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000279 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000280 LValue SrcLV =
281 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
282
283 // Store the value using the source type pointer.
284 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
285
286 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000287 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000288 }
289 CapturedVars.push_back(CV);
290 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000291 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000292 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000293 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000294 }
295}
296
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000297static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
298 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000299 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000300 ASTContext &Ctx = CGF.getContext();
301
Alexey Bataevddf3db92018-04-13 17:31:06 +0000302 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
303 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
304 Ctx.getPointerType(DstType), Loc);
305 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000306 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
307 .getAddress();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000308 return TmpAddr;
309}
310
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000311static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000312 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000313 return C.getLValueReferenceType(
314 getCanonicalParamType(C, T.getNonReferenceType()),
315 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000316 if (T->isPointerType())
317 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000318 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
319 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000320 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000321 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000322 return C.getCanonicalType(T);
323 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000324 return C.getCanonicalParamType(T);
325}
326
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000327namespace {
328 /// Contains required data for proper outlined function codegen.
329 struct FunctionOptions {
330 /// Captured statement for which the function is generated.
331 const CapturedStmt *S = nullptr;
332 /// true if cast to/from UIntPtr is required for variables captured by
333 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000334 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000335 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000336 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000337 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000338 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000339 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000340 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
341 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000342 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
344 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000345 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000346 };
347}
348
Alexey Bataeve754b182017-08-09 19:38:53 +0000349static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000351 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 &LocalAddrs,
353 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
354 &VLASizes,
355 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
356 const CapturedDecl *CD = FO.S->getCapturedDecl();
357 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000358 assert(CD->hasBody() && "missing CapturedDecl body");
359
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000361 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000362 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000363 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000364 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000365 Args.append(CD->param_begin(),
366 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000367 TargetArgs.append(
368 CD->param_begin(),
369 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000371 FunctionDecl *DebugFunctionDecl = nullptr;
372 if (!FO.UIntPtrCastRequired) {
373 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000374 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000375 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000376 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000377 SourceLocation(), DeclarationName(), FunctionTy,
378 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
379 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000380 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000381 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000382 QualType ArgType = FD->getType();
383 IdentifierInfo *II = nullptr;
384 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000385
386 // If this is a capture by copy and the type is not a pointer, the outlined
387 // function argument type should be uintptr and the value properly casted to
388 // uintptr. This is necessary given that the runtime library is only able to
389 // deal with pointers. We can pass in the same way the VLA type sizes to the
390 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000391 if (FO.UIntPtrCastRequired &&
392 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
393 I->capturesVariableArrayType()))
394 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000395
396 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 CapVar = I->getCapturedVar();
398 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000399 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000400 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000401 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000402 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000403 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000404 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000405 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000406 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000407 VarDecl *Arg;
408 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
409 Arg = ParmVarDecl::Create(
410 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000411 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000412 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
413 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
414 } else {
415 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
416 II, ArgType, ImplicitParamDecl::Other);
417 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000418 Args.emplace_back(Arg);
419 // Do not cast arguments if we emit function with non-original types.
420 TargetArgs.emplace_back(
421 FO.UIntPtrCastRequired
422 ? Arg
423 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000424 ++I;
425 }
426 Args.append(
427 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
428 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000429 TargetArgs.append(
430 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
431 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000432
433 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000434 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000435 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000436 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
437
Alexey Bataevddf3db92018-04-13 17:31:06 +0000438 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000439 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
440 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
442 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000443 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000444 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000445
446 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000447 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000448 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000450 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000451 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 // Do not map arguments if we emit function with non-original types.
453 Address LocalAddr(Address::invalid());
454 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
455 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
456 TargetArgs[Cnt]);
457 } else {
458 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
459 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000460 // If we are capturing a pointer by copy we don't need to do anything, just
461 // use the value that we get from the arguments.
462 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000463 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000464 if (!FO.RegisterCastedArgsOnly)
465 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000466 ++Cnt;
467 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000468 continue;
469 }
470
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000471 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
472 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000473 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000474 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000475 ArgLVal = CGF.MakeAddrLValue(
476 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
477 Args[Cnt]->getName(), ArgLVal),
478 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000479 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000480 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
481 const VariableArrayType *VAT = FD->getCapturedVLAType();
482 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000483 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000484 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000485 QualType VarTy = Var->getType();
486 Address ArgAddr = ArgLVal.getAddress();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000487 if (ArgLVal.getType()->isLValueReferenceType()) {
488 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
489 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
490 assert(ArgLVal.getType()->isPointerType());
491 ArgAddr = CGF.EmitLoadOfPointer(
492 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000493 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000494 if (!FO.RegisterCastedArgsOnly) {
495 LocalAddrs.insert(
496 {Args[Cnt],
497 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
498 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000499 } else if (I->capturesVariableByCopy()) {
500 assert(!FD->getType()->isAnyPointerType() &&
501 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000502 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000503 LocalAddrs.insert({Args[Cnt],
504 {Var, FO.UIntPtrCastRequired
505 ? castValueFromUintptr(
506 CGF, I->getLocation(), FD->getType(),
507 Args[Cnt]->getName(), ArgLVal)
508 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000509 } else {
510 // If 'this' is captured, load it into CXXThisValue.
511 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000512 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000513 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000514 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000515 ++Cnt;
516 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517 }
518
Alexey Bataeve754b182017-08-09 19:38:53 +0000519 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520}
521
522llvm::Function *
523CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
524 assert(
525 CapturedStmtInfo &&
526 "CapturedStmtInfo should be set when generating the captured function");
527 const CapturedDecl *CD = S.getCapturedDecl();
528 // Build the argument list.
529 bool NeedWrapperFunction =
530 getDebugInfo() &&
531 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
532 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000533 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000534 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000535 SmallString<256> Buffer;
536 llvm::raw_svector_ostream Out(Buffer);
537 Out << CapturedStmtInfo->getHelperName();
538 if (NeedWrapperFunction)
539 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000540 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000541 Out.str());
542 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
543 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000544 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000545 for (const auto &LocalAddrPair : LocalAddrs) {
546 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000547 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
548 return LocalAddrPair.second.second;
549 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000550 }
551 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000552 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000553 for (const auto &VLASizePair : VLASizes)
554 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000555 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000556 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000557 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000558 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000559 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000560 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000561
Alexey Bataevefd884d2017-08-04 21:26:25 +0000562 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000563 /*RegisterCastedArgsOnly=*/true,
564 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000565 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000566 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000567 Args.clear();
568 LocalAddrs.clear();
569 VLASizes.clear();
570 llvm::Function *WrapperF =
571 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000572 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000573 llvm::SmallVector<llvm::Value *, 4> CallArgs;
574 for (const auto *Arg : Args) {
575 llvm::Value *CallArg;
576 auto I = LocalAddrs.find(Arg);
577 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000578 LValue LV = WrapperCGF.MakeAddrLValue(
579 I->second.second,
580 I->second.first ? I->second.first->getType() : Arg->getType(),
581 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000582 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000583 } else {
584 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000585 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000586 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000587 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000588 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000589 Arg->getType(),
590 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000591 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000592 }
593 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000594 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000595 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000596 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000597 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000598 WrapperCGF.FinishFunction();
599 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000600}
601
Alexey Bataev9959db52014-05-06 10:08:46 +0000602//===----------------------------------------------------------------------===//
603// OpenMP Directive Emission
604//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000605void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000606 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000607 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000608 // Perform element-by-element initialization.
609 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000610
611 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000612 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
613 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000614 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
615
Alexey Bataevddf3db92018-04-13 17:31:06 +0000616 llvm::Value *SrcBegin = SrcAddr.getPointer();
617 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000618 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000619 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000620 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000621 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
622 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
623 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000624 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
625 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000626
Alexey Bataev420d45b2015-04-14 05:11:24 +0000627 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000628 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000630
631 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
632
633 llvm::PHINode *SrcElementPHI =
634 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
635 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
636 Address SrcElementCurrent =
637 Address(SrcElementPHI,
638 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
639
640 llvm::PHINode *DestElementPHI =
641 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
642 DestElementPHI->addIncoming(DestBegin, EntryBB);
643 Address DestElementCurrent =
644 Address(DestElementPHI,
645 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000646
Alexey Bataev420d45b2015-04-14 05:11:24 +0000647 // Emit copy.
648 CopyGen(DestElementCurrent, SrcElementCurrent);
649
650 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000651 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000652 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000653 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000654 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000655 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000656 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000657 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
658 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000659 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
660 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000661
662 // Done.
663 EmitBlock(DoneBB, /*IsFinished=*/true);
664}
665
John McCall7f416cc2015-09-08 08:05:57 +0000666void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
667 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000668 const VarDecl *SrcVD, const Expr *Copy) {
669 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000670 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000671 if (BO && BO->getOpcode() == BO_Assign) {
672 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000673 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
674 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
675 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000676 } else {
677 // For arrays with complex element types perform element by element
678 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000679 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000680 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000681 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000682 // Working with the single array element, so have to remap
683 // destination and source variables to corresponding array
684 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000685 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000686 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
687 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000688 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000689 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000690 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000691 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000692 } else {
693 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000694 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000695 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
696 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000697 (void)Remap.Privatize();
698 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000699 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000700 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000701}
702
Alexey Bataev69c62a92015-04-15 04:52:20 +0000703bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
704 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000705 if (!HaveInsertPoint())
706 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000707 bool DeviceConstTarget =
708 getLangOpts().OpenMPIsDevice &&
709 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000710 bool FirstprivateIsLastprivate = false;
711 llvm::DenseSet<const VarDecl *> Lastprivates;
712 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
713 for (const auto *D : C->varlists())
714 Lastprivates.insert(
715 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
716 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000717 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000718 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
719 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
720 // Force emission of the firstprivate copy if the directive does not emit
721 // outlined function, like omp for, omp simd, omp distribute etc.
722 bool MustEmitFirstprivateCopy =
723 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000724 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 auto IRef = C->varlist_begin();
726 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000727 for (const Expr *IInit : C->private_copies()) {
728 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000729 bool ThisFirstprivateIsLastprivate =
730 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000731 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000732 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000733 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000734 !FD->getType()->isReferenceType() &&
735 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000736 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
737 ++IRef;
738 ++InitsRef;
739 continue;
740 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000741 // Do not emit copy for firstprivate constant variables in target regions,
742 // captured by reference.
743 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000744 FD && FD->getType()->isReferenceType() &&
745 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000746 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
747 OrigVD);
748 ++IRef;
749 ++InitsRef;
750 continue;
751 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000752 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000753 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000754 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000755 const auto *VDInit =
756 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000757 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000758 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000759 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
760 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000761 LValue OriginalLVal = EmitLValue(&DRE);
Alexey Bataevfeddd642016-04-22 09:05:03 +0000762 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000763 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000764 // Emit VarDecl with copy init for arrays.
765 // Get the address of the original variable captured in current
766 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000767 IsRegistered = PrivateScope.addPrivate(
768 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
769 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
770 const Expr *Init = VD->getInit();
771 if (!isa<CXXConstructExpr>(Init) ||
772 isTrivialInitializer(Init)) {
773 // Perform simple memcpy.
774 LValue Dest =
775 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
776 EmitAggregateAssign(Dest, OriginalLVal, Type);
777 } else {
778 EmitOMPAggregateAssign(
779 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
780 Type,
781 [this, VDInit, Init](Address DestElement,
782 Address SrcElement) {
783 // Clean up any temporaries needed by the
784 // initialization.
785 RunCleanupsScope InitScope(*this);
786 // Emit initialization for single element.
787 setAddrOfLocalVar(VDInit, SrcElement);
788 EmitAnyExprToMem(Init, DestElement,
789 Init->getType().getQualifiers(),
790 /*IsInitializer*/ false);
791 LocalDeclMap.erase(VDInit);
792 });
793 }
794 EmitAutoVarCleanups(Emission);
795 return Emission.getAllocatedAddress();
796 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000797 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000798 Address OriginalAddr = OriginalLVal.getAddress();
799 IsRegistered = PrivateScope.addPrivate(
800 OrigVD, [this, VDInit, OriginalAddr, VD]() {
801 // Emit private VarDecl with copy init.
802 // Remap temp VDInit variable to the address of the original
803 // variable (for proper handling of captured global variables).
804 setAddrOfLocalVar(VDInit, OriginalAddr);
805 EmitDecl(*VD);
806 LocalDeclMap.erase(VDInit);
807 return GetAddrOfLocalVar(VD);
808 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000809 }
810 assert(IsRegistered &&
811 "firstprivate var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000815 ++IRef;
816 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000817 }
818 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000819 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000820}
821
Alexey Bataev03b340a2014-10-21 03:16:40 +0000822void CodeGenFunction::EmitOMPPrivateClause(
823 const OMPExecutableDirective &D,
824 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000825 if (!HaveInsertPoint())
826 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000827 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000828 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000829 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000830 for (const Expr *IInit : C->private_copies()) {
831 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000832 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000833 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
834 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
835 // Emit private VarDecl with copy init.
836 EmitDecl(*VD);
837 return GetAddrOfLocalVar(VD);
838 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000839 assert(IsRegistered && "private var already registered as private");
840 // Silence the warning about unused variable.
841 (void)IsRegistered;
842 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000843 ++IRef;
844 }
845 }
846}
847
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000848bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000849 if (!HaveInsertPoint())
850 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000851 // threadprivate_var1 = master_threadprivate_var1;
852 // operator=(threadprivate_var2, master_threadprivate_var2);
853 // ...
854 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855 llvm::DenseSet<const VarDecl *> CopiedVars;
856 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000857 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000858 auto IRef = C->varlist_begin();
859 auto ISrcRef = C->source_exprs().begin();
860 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000861 for (const Expr *AssignOp : C->assignment_ops()) {
862 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000863 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000864 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000865 // Get the address of the master variable. If we are emitting code with
866 // TLS support, the address is passed from the master as field in the
867 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000868 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000869 if (getLangOpts().OpenMPUseTLS &&
870 getContext().getTargetInfo().isTLSSupported()) {
871 assert(CapturedStmtInfo->lookup(VD) &&
872 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000873 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
874 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000875 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000876 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000877 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000878 MasterAddr =
879 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
880 : CGM.GetAddrOfGlobal(VD),
881 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000882 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000883 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000884 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000885 if (CopiedVars.size() == 1) {
886 // At first check if current thread is a master thread. If it is, no
887 // need to copy data.
888 CopyBegin = createBasicBlock("copyin.not.master");
889 CopyEnd = createBasicBlock("copyin.not.master.end");
890 Builder.CreateCondBr(
891 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000892 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000893 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
894 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000895 CopyBegin, CopyEnd);
896 EmitBlock(CopyBegin);
897 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000898 const auto *SrcVD =
899 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
900 const auto *DestVD =
901 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000902 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000903 }
904 ++IRef;
905 ++ISrcRef;
906 ++IDestRef;
907 }
908 }
909 if (CopyEnd) {
910 // Exit out of copying procedure for non-master thread.
911 EmitBlock(CopyEnd, /*IsFinished=*/true);
912 return true;
913 }
914 return false;
915}
916
Alexey Bataev38e89532015-04-16 04:54:05 +0000917bool CodeGenFunction::EmitOMPLastprivateClauseInit(
918 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000919 if (!HaveInsertPoint())
920 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000921 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000922 llvm::DenseSet<const VarDecl *> SIMDLCVs;
923 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000924 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
925 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000926 SIMDLCVs.insert(
927 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
928 }
929 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000930 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000931 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000932 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000933 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
934 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000935 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000936 auto IRef = C->varlist_begin();
937 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000938 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000939 // Keep the address of the original variable for future update at the end
940 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000941 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000942 // Taskloops do not require additional initialization, it is done in
943 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000944 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000945 const auto *DestVD =
946 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
947 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000948 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
949 /*RefersToEnclosingVariableOrCapture=*/
950 CapturedStmtInfo->lookup(OrigVD) != nullptr,
951 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +0000952 return EmitLValue(&DRE).getAddress();
953 });
954 // Check if the variable is also a firstprivate: in this case IInit is
955 // not generated. Initialization of this variable will happen in codegen
956 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000957 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000958 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
959 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +0000960 // Emit private VarDecl with copy init.
961 EmitDecl(*VD);
962 return GetAddrOfLocalVar(VD);
963 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000964 assert(IsRegistered &&
965 "lastprivate var already registered as private");
966 (void)IsRegistered;
967 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000968 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000969 ++IRef;
970 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000971 }
972 }
973 return HasAtLeastOneLastprivate;
974}
975
976void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000977 const OMPExecutableDirective &D, bool NoFinals,
978 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000979 if (!HaveInsertPoint())
980 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000981 // Emit following code:
982 // if (<IsLastIterCond>) {
983 // orig_var1 = private_orig_var1;
984 // ...
985 // orig_varn = private_orig_varn;
986 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000987 llvm::BasicBlock *ThenBB = nullptr;
988 llvm::BasicBlock *DoneBB = nullptr;
989 if (IsLastIterCond) {
990 ThenBB = createBasicBlock(".omp.lastprivate.then");
991 DoneBB = createBasicBlock(".omp.lastprivate.done");
992 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
993 EmitBlock(ThenBB);
994 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000995 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
996 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000997 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000998 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000999 for (const Expr *F : LoopDirective->finals()) {
1000 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001001 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1002 if (NoFinals)
1003 AlreadyEmittedVars.insert(D);
1004 else
1005 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001006 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001007 }
1008 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001009 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1010 auto IRef = C->varlist_begin();
1011 auto ISrcRef = C->source_exprs().begin();
1012 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001013 for (const Expr *AssignOp : C->assignment_ops()) {
1014 const auto *PrivateVD =
1015 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001016 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001017 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001018 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1019 // If lastprivate variable is a loop control variable for loop-based
1020 // directive, update its value before copyin back to original
1021 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001022 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001023 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001024 const auto *SrcVD =
1025 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1026 const auto *DestVD =
1027 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001028 // Get the address of the original variable.
1029 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1030 // Get the address of the private variable.
1031 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001032 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001033 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001034 Address(Builder.CreateLoad(PrivateAddr),
1035 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001036 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001037 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001038 ++IRef;
1039 ++ISrcRef;
1040 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001041 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001042 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001043 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001044 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001045 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001046 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001047}
1048
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001049void CodeGenFunction::EmitOMPReductionClauseInit(
1050 const OMPExecutableDirective &D,
1051 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001052 if (!HaveInsertPoint())
1053 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001054 SmallVector<const Expr *, 4> Shareds;
1055 SmallVector<const Expr *, 4> Privates;
1056 SmallVector<const Expr *, 4> ReductionOps;
1057 SmallVector<const Expr *, 4> LHSs;
1058 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001059 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001060 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001061 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001062 auto ILHS = C->lhs_exprs().begin();
1063 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001064 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001065 Shareds.emplace_back(Ref);
1066 Privates.emplace_back(*IPriv);
1067 ReductionOps.emplace_back(*IRed);
1068 LHSs.emplace_back(*ILHS);
1069 RHSs.emplace_back(*IRHS);
1070 std::advance(IPriv, 1);
1071 std::advance(IRed, 1);
1072 std::advance(ILHS, 1);
1073 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001074 }
1075 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001076 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1077 unsigned Count = 0;
1078 auto ILHS = LHSs.begin();
1079 auto IRHS = RHSs.begin();
1080 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001081 for (const Expr *IRef : Shareds) {
1082 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001083 // Emit private VarDecl with reduction init.
1084 RedCG.emitSharedLValue(*this, Count);
1085 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001086 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001087 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1088 RedCG.getSharedLValue(Count),
1089 [&Emission](CodeGenFunction &CGF) {
1090 CGF.EmitAutoVarInit(Emission);
1091 return true;
1092 });
1093 EmitAutoVarCleanups(Emission);
1094 Address BaseAddr = RedCG.adjustPrivateAddress(
1095 *this, Count, Emission.getAllocatedAddress());
1096 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001097 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001098 assert(IsRegistered && "private var already registered as private");
1099 // Silence the warning about unused variable.
1100 (void)IsRegistered;
1101
Alexey Bataevddf3db92018-04-13 17:31:06 +00001102 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1103 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001104 QualType Type = PrivateVD->getType();
1105 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1106 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001107 // Store the address of the original variable associated with the LHS
1108 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001109 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001110 return RedCG.getSharedLValue(Count).getAddress();
1111 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001112 PrivateScope.addPrivate(
1113 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001114 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1115 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 // Store the address of the original variable associated with the LHS
1117 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001118 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001119 return RedCG.getSharedLValue(Count).getAddress();
1120 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001121 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001122 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1123 ConvertTypeForMem(RHSVD->getType()),
1124 "rhs.begin");
1125 });
1126 } else {
1127 QualType Type = PrivateVD->getType();
1128 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1129 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1130 // Store the address of the original variable associated with the LHS
1131 // implicit variable.
1132 if (IsArray) {
1133 OriginalAddr = Builder.CreateElementBitCast(
1134 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1135 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001136 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001137 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001138 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 return IsArray
1140 ? Builder.CreateElementBitCast(
1141 GetAddrOfLocalVar(PrivateVD),
1142 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1143 : GetAddrOfLocalVar(PrivateVD);
1144 });
1145 }
1146 ++ILHS;
1147 ++IRHS;
1148 ++IPriv;
1149 ++Count;
1150 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001151}
1152
1153void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001154 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001155 if (!HaveInsertPoint())
1156 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001157 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158 llvm::SmallVector<const Expr *, 8> LHSExprs;
1159 llvm::SmallVector<const Expr *, 8> RHSExprs;
1160 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001161 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001162 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001163 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001164 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1166 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1167 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1168 }
1169 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001170 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1171 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001172 ReductionKind == OMPD_simd;
1173 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001174 // Emit nowait reduction if nowait clause is present or directive is a
1175 // parallel directive (it always has implicit barrier).
1176 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001177 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001178 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001179 }
1180}
1181
Alexey Bataev61205072016-03-02 04:57:40 +00001182static void emitPostUpdateForReductionClause(
1183 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001184 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001185 if (!CGF.HaveInsertPoint())
1186 return;
1187 llvm::BasicBlock *DoneBB = nullptr;
1188 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001189 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001190 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001191 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001192 // If the first post-update expression is found, emit conditional
1193 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001194 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001195 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1196 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1197 CGF.EmitBlock(ThenBB);
1198 }
1199 }
1200 CGF.EmitIgnoredExpr(PostUpdate);
1201 }
1202 }
1203 if (DoneBB)
1204 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1205}
1206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001207namespace {
1208/// Codegen lambda for appending distribute lower and upper bounds to outlined
1209/// parallel function. This is necessary for combined constructs such as
1210/// 'distribute parallel for'
1211typedef llvm::function_ref<void(CodeGenFunction &,
1212 const OMPExecutableDirective &,
1213 llvm::SmallVectorImpl<llvm::Value *> &)>
1214 CodeGenBoundParametersTy;
1215} // anonymous namespace
1216
1217static void emitCommonOMPParallelDirective(
1218 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1219 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1220 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001221 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001222 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001223 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1224 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001225 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001226 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001227 llvm::Value *NumThreads =
1228 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1229 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001230 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001231 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001232 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001233 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001234 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001235 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001236 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001237 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001238 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001239 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1240 if (C->getNameModifier() == OMPD_unknown ||
1241 C->getNameModifier() == OMPD_parallel) {
1242 IfCond = C->getCondition();
1243 break;
1244 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001245 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001246
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001247 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001248 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001249 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1250 // lower and upper bounds with the pragma 'for' chunking mechanism.
1251 // The following lambda takes care of appending the lower and upper bound
1252 // parameters when necessary
1253 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001254 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001255 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001256 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001257}
1258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001259static void emitEmptyBoundParameters(CodeGenFunction &,
1260 const OMPExecutableDirective &,
1261 llvm::SmallVectorImpl<llvm::Value *> &) {}
1262
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001265 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001266 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001268 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001269 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1270 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001271 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001272 // propagation master's thread values of threadprivate variables to local
1273 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001274 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001275 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001276 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001277 }
1278 CGF.EmitOMPPrivateClause(S, PrivateScope);
1279 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1280 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001281 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001282 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001283 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001284 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1285 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001286 emitPostUpdateForReductionClause(*this, S,
1287 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001288}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001289
Alexey Bataev0f34da12015-07-02 04:17:07 +00001290void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1291 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 RunCleanupsScope BodyScope(*this);
1293 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001294 for (const Expr *UE : D.updates())
1295 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001296 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001297 // In distribute directives only loop counters may be marked as linear, no
1298 // need to generate the code for them.
1299 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001301 for (const Expr *UE : C->updates())
1302 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001303 }
Alexander Musman3276a272015-03-21 10:12:56 +00001304 }
1305
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001307 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001308 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001311 // The end (updates/cleanups).
1312 EmitBlock(Continue.getBlock());
1313 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314}
1315
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316void CodeGenFunction::EmitOMPInnerLoop(
1317 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1318 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001319 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1320 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001321 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001322
1323 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001324 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001325 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001326 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001327 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1328 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001329
1330 // If there are any cleanups between here and the loop-exit scope,
1331 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001332 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001333 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
Alexey Bataevddf3db92018-04-13 17:31:06 +00001336 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001337
Alexey Bataev2df54a02015-03-12 08:53:29 +00001338 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001339 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001340 if (ExitBlock != LoopExit.getBlock()) {
1341 EmitBlock(ExitBlock);
1342 EmitBranchThroughCleanup(LoopExit);
1343 }
1344
1345 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001346 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001347
1348 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001349 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001350 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1351
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353
1354 // Emit "IV = IV + 1" and a back-edge to the condition block.
1355 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001356 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001357 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358 BreakContinueStack.pop_back();
1359 EmitBranch(CondBlock);
1360 LoopStack.pop();
1361 // Emit the fall-through block.
1362 EmitBlock(LoopExit.getBlock());
1363}
1364
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001365bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001366 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001369 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001370 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001371 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001372 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001373 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1374 if (const auto *Ref =
1375 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001376 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001377 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001378 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001379 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1380 VD->getInit()->getType(), VK_LValue,
1381 VD->getInit()->getExprLoc());
1382 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1383 VD->getType()),
1384 /*capturedByInit=*/false);
1385 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001386 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001387 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001388 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001389 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001390 // Emit the linear steps for the linear clauses.
1391 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001392 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1393 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001394 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001395 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001396 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001397 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001398 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001399 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001400}
1401
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001402void CodeGenFunction::EmitOMPLinearClauseFinal(
1403 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001404 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001405 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001406 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001407 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001408 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001409 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001410 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001411 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001412 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001413 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001414 // If the first post-update expression is found, emit conditional
1415 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001416 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001417 DoneBB = createBasicBlock(".omp.linear.pu.done");
1418 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1419 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001420 }
1421 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001422 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001423 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001426 Address OrigAddr = EmitLValue(&DRE).getAddress();
1427 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001428 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001429 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001430 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001431 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001432 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001433 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001434 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001435 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001436 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001437 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001438}
1439
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001440static void emitAlignedClause(CodeGenFunction &CGF,
1441 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001442 if (!CGF.HaveInsertPoint())
1443 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001444 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001445 unsigned ClauseAlignment = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001446 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1447 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001448 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1449 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001450 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001451 for (const Expr *E : Clause->varlists()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001452 unsigned Alignment = ClauseAlignment;
1453 if (Alignment == 0) {
1454 // OpenMP [2.8.1, Description]
1455 // If no optional parameter is specified, implementation-defined default
1456 // alignments for SIMD instructions on the target platforms are assumed.
1457 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001458 CGF.getContext()
1459 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1460 E->getType()->getPointeeType()))
1461 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001462 }
1463 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1464 "alignment is not power of 2");
1465 if (Alignment != 0) {
1466 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001467 CGF.EmitAlignmentAssumption(
1468 PtrValue, E, /*No second loc needed*/ SourceLocation(), Alignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001469 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001470 }
1471 }
1472}
1473
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001474void CodeGenFunction::EmitOMPPrivateLoopCounters(
1475 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1476 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001477 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001479 for (const Expr *E : S.counters()) {
1480 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1481 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001482 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001483 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001484 EmitAutoVarCleanups(VarEmission);
1485 LocalDeclMap.erase(PrivateVD);
1486 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1487 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001488 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001489 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1490 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001491 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001492 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001493 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1494 E->getType(), VK_LValue, E->getExprLoc());
1495 return EmitLValue(&DRE).getAddress();
1496 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001497 } else {
1498 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1499 return VarEmission.getAllocatedAddress();
1500 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001501 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001502 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001503 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001504 // Privatize extra loop counters used in loops for ordered(n) clauses.
1505 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1506 if (!C->getNumForLoops())
1507 continue;
1508 for (unsigned I = S.getCollapsedNumber(),
1509 E = C->getLoopNumIterations().size();
1510 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001511 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001512 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001513 // Override only those variables that can be captured to avoid re-emission
1514 // of the variables declared within the loops.
1515 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001516 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1517 return CreateMemTemp(DRE->getType(), VD->getName());
1518 });
1519 }
1520 }
1521 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001522}
1523
Alexey Bataev62dbb972015-04-22 11:59:37 +00001524static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1525 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1526 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001527 if (!CGF.HaveInsertPoint())
1528 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001529 {
1530 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001531 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001532 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001533 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001534 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001535 CGF.EmitIgnoredExpr(I);
1536 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001537 }
1538 // Check that loop is executed at least one time.
1539 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1540}
1541
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001542void CodeGenFunction::EmitOMPLinearClause(
1543 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1544 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001545 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001546 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1547 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001548 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1549 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001550 SIMDLCVs.insert(
1551 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1552 }
1553 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001554 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001555 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001556 for (const Expr *E : C->varlists()) {
1557 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1558 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001559 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001561 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001562 // Emit private VarDecl with copy init.
1563 EmitVarDecl(*PrivateVD);
1564 return GetAddrOfLocalVar(PrivateVD);
1565 });
1566 assert(IsRegistered && "linear var already registered as private");
1567 // Silence the warning about unused variable.
1568 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001569 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001570 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001571 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001572 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001573 }
1574 }
1575}
1576
Alexey Bataev45bfad52015-08-21 12:19:04 +00001577static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001578 const OMPExecutableDirective &D,
1579 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001580 if (!CGF.HaveInsertPoint())
1581 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001582 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001583 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1584 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001585 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001586 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1587 // In presence of finite 'safelen', it may be unsafe to mark all
1588 // the memory instructions parallel, because loop-carried
1589 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001590 if (!IsMonotonic)
1591 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001592 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001593 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1594 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001595 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001596 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001597 // In presence of finite 'safelen', it may be unsafe to mark all
1598 // the memory instructions parallel, because loop-carried
1599 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001600 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001601 }
1602}
1603
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001604void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1605 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001606 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001607 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001608 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001609 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001610}
1611
Alexey Bataevef549a82016-03-09 09:49:09 +00001612void CodeGenFunction::EmitOMPSimdFinal(
1613 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001614 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001615 if (!HaveInsertPoint())
1616 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001617 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001618 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001619 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001620 for (const Expr *F : D.finals()) {
1621 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1622 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1623 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001624 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1625 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001626 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001627 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001628 // If the first post-update expression is found, emit conditional
1629 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001630 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001631 DoneBB = createBasicBlock(".omp.final.done");
1632 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1633 EmitBlock(ThenBB);
1634 }
1635 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001636 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001637 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001638 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001639 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001640 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001641 /*RefersToEnclosingVariableOrCapture=*/false,
1642 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1643 OrigAddr = EmitLValue(&DRE).getAddress();
1644 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001645 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001646 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001647 (void)VarScope.Privatize();
1648 EmitIgnoredExpr(F);
1649 }
1650 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001651 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001652 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001653 if (DoneBB)
1654 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001655}
1656
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001657static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1658 const OMPLoopDirective &S,
1659 CodeGenFunction::JumpDest LoopExit) {
1660 CGF.EmitOMPLoopBody(S, LoopExit);
1661 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001662}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001663
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001664/// Emit a helper variable and return corresponding lvalue.
1665static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1666 const DeclRefExpr *Helper) {
1667 auto VDecl = cast<VarDecl>(Helper->getDecl());
1668 CGF.EmitVarDecl(*VDecl);
1669 return CGF.EmitLValue(Helper);
1670}
1671
Alexey Bataevf8365372017-11-17 17:57:25 +00001672static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1673 PrePostActionTy &Action) {
1674 Action.Enter(CGF);
1675 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1676 "Expected simd directive");
1677 OMPLoopScope PreInitScope(CGF, S);
1678 // if (PreCond) {
1679 // for (IV in 0..LastIteration) BODY;
1680 // <Final counter/linear vars updates>;
1681 // }
1682 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001683 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1684 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1685 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1686 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1687 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1688 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001689
Alexey Bataevf8365372017-11-17 17:57:25 +00001690 // Emit: if (PreCond) - begin.
1691 // If the condition constant folds and can be elided, avoid emitting the
1692 // whole loop.
1693 bool CondConstant;
1694 llvm::BasicBlock *ContBlock = nullptr;
1695 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1696 if (!CondConstant)
1697 return;
1698 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001699 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001700 ContBlock = CGF.createBasicBlock("simd.if.end");
1701 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1702 CGF.getProfileCount(&S));
1703 CGF.EmitBlock(ThenBlock);
1704 CGF.incrementProfileCounter(&S);
1705 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001706
Alexey Bataevf8365372017-11-17 17:57:25 +00001707 // Emit the loop iteration variable.
1708 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001709 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001710 CGF.EmitVarDecl(*IVDecl);
1711 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001712
Alexey Bataevf8365372017-11-17 17:57:25 +00001713 // Emit the iterations count variable.
1714 // If it is not a variable, Sema decided to calculate iterations count on
1715 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001716 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001717 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1718 // Emit calculation of the iterations count.
1719 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1720 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001721
Alexey Bataevf8365372017-11-17 17:57:25 +00001722 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001723
Alexey Bataevf8365372017-11-17 17:57:25 +00001724 emitAlignedClause(CGF, S);
1725 (void)CGF.EmitOMPLinearClauseInit(S);
1726 {
1727 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1728 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1729 CGF.EmitOMPLinearClause(S, LoopScope);
1730 CGF.EmitOMPPrivateClause(S, LoopScope);
1731 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1732 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1733 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001734 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1735 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevf8365372017-11-17 17:57:25 +00001736 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1737 S.getInc(),
1738 [&S](CodeGenFunction &CGF) {
1739 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1740 CGF.EmitStopPoint(&S);
1741 },
1742 [](CodeGenFunction &) {});
Alexey Bataevddf3db92018-04-13 17:31:06 +00001743 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001744 // Emit final copy of the lastprivate variables at the end of loops.
1745 if (HasLastprivateClause)
1746 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1747 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001748 emitPostUpdateForReductionClause(CGF, S,
1749 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001750 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001751 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001752 // Emit: if (PreCond) - end.
1753 if (ContBlock) {
1754 CGF.EmitBranch(ContBlock);
1755 CGF.EmitBlock(ContBlock, true);
1756 }
1757}
1758
1759void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1760 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1761 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001762 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001763 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001764 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001765}
1766
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001767void CodeGenFunction::EmitOMPOuterLoop(
1768 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1769 CodeGenFunction::OMPPrivateScope &LoopScope,
1770 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1771 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1772 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001773 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001774
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001775 const Expr *IVExpr = S.getIterationVariable();
1776 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1777 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1778
Alexey Bataevddf3db92018-04-13 17:31:06 +00001779 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001780
1781 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001782 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001783 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001784 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001785 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1786 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001787
1788 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001789 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001790 // UB = min(UB, GlobalUB) or
1791 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1792 // 'distribute parallel for')
1793 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001794 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001795 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001796 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001797 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001798 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001799 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001800 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001801 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001802 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001803
1804 // If there are any cleanups between here and the loop-exit scope,
1805 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001806 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001807 if (LoopScope.requiresCleanups())
1808 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1809
Alexey Bataevddf3db92018-04-13 17:31:06 +00001810 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001811 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1812 if (ExitBlock != LoopExit.getBlock()) {
1813 EmitBlock(ExitBlock);
1814 EmitBranchThroughCleanup(LoopExit);
1815 }
1816 EmitBlock(LoopBody);
1817
Alexander Musman92bdaab2015-03-12 13:37:50 +00001818 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1819 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001820 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001821 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001822
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001823 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001824 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001825 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1826
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001827 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1828 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001829 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1830 LoopStack.setParallel(!IsMonotonic);
1831 else
1832 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001833
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001834 SourceLocation Loc = S.getBeginLoc();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001835
1836 // when 'distribute' is not combined with a 'for':
1837 // while (idx <= UB) { BODY; ++idx; }
1838 // when 'distribute' is combined with a 'for'
1839 // (e.g. 'distribute parallel for')
1840 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1841 EmitOMPInnerLoop(
1842 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1843 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1844 CodeGenLoop(CGF, S, LoopExit);
1845 },
1846 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1847 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1848 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001849
1850 EmitBlock(Continue.getBlock());
1851 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001852 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001853 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001854 EmitIgnoredExpr(LoopArgs.NextLB);
1855 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001856 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001857
1858 EmitBranch(CondBlock);
1859 LoopStack.pop();
1860 // Emit the fall-through block.
1861 EmitBlock(LoopExit.getBlock());
1862
1863 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001864 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1865 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001866 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00001867 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001868 };
1869 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001870}
1871
1872void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001873 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001874 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001875 const OMPLoopArguments &LoopArgs,
1876 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001877 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001878
1879 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001880 const bool DynamicOrOrdered =
1881 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001882
1883 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001884 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001885 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001886 "static non-chunked schedule does not need outer loop");
1887
1888 // Emit outer loop.
1889 //
1890 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1891 // When schedule(dynamic,chunk_size) is specified, the iterations are
1892 // distributed to threads in the team in chunks as the threads request them.
1893 // Each thread executes a chunk of iterations, then requests another chunk,
1894 // until no chunks remain to be distributed. Each chunk contains chunk_size
1895 // iterations, except for the last chunk to be distributed, which may have
1896 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1897 //
1898 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1899 // to threads in the team in chunks as the executing threads request them.
1900 // Each thread executes a chunk of iterations, then requests another chunk,
1901 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1902 // each chunk is proportional to the number of unassigned iterations divided
1903 // by the number of threads in the team, decreasing to 1. For a chunk_size
1904 // with value k (greater than 1), the size of each chunk is determined in the
1905 // same way, with the restriction that the chunks do not contain fewer than k
1906 // iterations (except for the last chunk to be assigned, which may have fewer
1907 // than k iterations).
1908 //
1909 // When schedule(auto) is specified, the decision regarding scheduling is
1910 // delegated to the compiler and/or runtime system. The programmer gives the
1911 // implementation the freedom to choose any possible mapping of iterations to
1912 // threads in the team.
1913 //
1914 // When schedule(runtime) is specified, the decision regarding scheduling is
1915 // deferred until run time, and the schedule and chunk size are taken from the
1916 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1917 // implementation defined
1918 //
1919 // while(__kmpc_dispatch_next(&LB, &UB)) {
1920 // idx = LB;
1921 // while (idx <= UB) { BODY; ++idx;
1922 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1923 // } // inner loop
1924 // }
1925 //
1926 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1927 // When schedule(static, chunk_size) is specified, iterations are divided into
1928 // chunks of size chunk_size, and the chunks are assigned to the threads in
1929 // the team in a round-robin fashion in the order of the thread number.
1930 //
1931 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1932 // while (idx <= UB) { BODY; ++idx; } // inner loop
1933 // LB = LB + ST;
1934 // UB = UB + ST;
1935 // }
1936 //
1937
1938 const Expr *IVExpr = S.getIterationVariable();
1939 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1940 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1941
1942 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001943 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
1944 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001945 llvm::Value *LBVal = DispatchBounds.first;
1946 llvm::Value *UBVal = DispatchBounds.second;
1947 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1948 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001949 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001950 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001951 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001952 CGOpenMPRuntime::StaticRTInput StaticInit(
1953 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1954 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001955 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001956 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001957 }
1958
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001959 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1960 const unsigned IVSize,
1961 const bool IVSigned) {
1962 if (Ordered) {
1963 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1964 IVSigned);
1965 }
1966 };
1967
1968 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1969 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1970 OuterLoopArgs.IncExpr = S.getInc();
1971 OuterLoopArgs.Init = S.getInit();
1972 OuterLoopArgs.Cond = S.getCond();
1973 OuterLoopArgs.NextLB = S.getNextLowerBound();
1974 OuterLoopArgs.NextUB = S.getNextUpperBound();
1975 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1976 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001977}
1978
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001979static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1980 const unsigned IVSize, const bool IVSigned) {}
1981
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001982void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001983 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1984 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1985 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001986
Alexey Bataevddf3db92018-04-13 17:31:06 +00001987 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001988
1989 // Emit outer loop.
1990 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1991 // dynamic
1992 //
1993
1994 const Expr *IVExpr = S.getIterationVariable();
1995 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1996 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1997
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001998 CGOpenMPRuntime::StaticRTInput StaticInit(
1999 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2000 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002001 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002002
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002003 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002004 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002005 Expr *IncExpr;
2006 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2007 IncExpr = S.getDistInc();
2008 else
2009 IncExpr = S.getInc();
2010
2011 // this routine is shared by 'omp distribute parallel for' and
2012 // 'omp distribute': select the right EUB expression depending on the
2013 // directive
2014 OMPLoopArguments OuterLoopArgs;
2015 OuterLoopArgs.LB = LoopArgs.LB;
2016 OuterLoopArgs.UB = LoopArgs.UB;
2017 OuterLoopArgs.ST = LoopArgs.ST;
2018 OuterLoopArgs.IL = LoopArgs.IL;
2019 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2020 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2021 ? S.getCombinedEnsureUpperBound()
2022 : S.getEnsureUpperBound();
2023 OuterLoopArgs.IncExpr = IncExpr;
2024 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2025 ? S.getCombinedInit()
2026 : S.getInit();
2027 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2028 ? S.getCombinedCond()
2029 : S.getCond();
2030 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2031 ? S.getCombinedNextLowerBound()
2032 : S.getNextLowerBound();
2033 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2034 ? S.getCombinedNextUpperBound()
2035 : S.getNextUpperBound();
2036
2037 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2038 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2039 emitEmptyOrdered);
2040}
2041
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002042static std::pair<LValue, LValue>
2043emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2044 const OMPExecutableDirective &S) {
2045 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2046 LValue LB =
2047 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2048 LValue UB =
2049 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2050
2051 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2052 // parallel for') we need to use the 'distribute'
2053 // chunk lower and upper bounds rather than the whole loop iteration
2054 // space. These are parameters to the outlined function for 'parallel'
2055 // and we copy the bounds of the previous schedule into the
2056 // the current ones.
2057 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2058 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002059 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2060 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002061 PrevLBVal = CGF.EmitScalarConversion(
2062 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002063 LS.getIterationVariable()->getType(),
2064 LS.getPrevLowerBoundVariable()->getExprLoc());
2065 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2066 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002067 PrevUBVal = CGF.EmitScalarConversion(
2068 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002069 LS.getIterationVariable()->getType(),
2070 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002071
2072 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2073 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2074
2075 return {LB, UB};
2076}
2077
2078/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2079/// we need to use the LB and UB expressions generated by the worksharing
2080/// code generation support, whereas in non combined situations we would
2081/// just emit 0 and the LastIteration expression
2082/// This function is necessary due to the difference of the LB and UB
2083/// types for the RT emission routines for 'for_static_init' and
2084/// 'for_dispatch_init'
2085static std::pair<llvm::Value *, llvm::Value *>
2086emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2087 const OMPExecutableDirective &S,
2088 Address LB, Address UB) {
2089 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2090 const Expr *IVExpr = LS.getIterationVariable();
2091 // when implementing a dynamic schedule for a 'for' combined with a
2092 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2093 // is not normalized as each team only executes its own assigned
2094 // distribute chunk
2095 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002096 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002097 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002098 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002099 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002100 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002101}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002102
2103static void emitDistributeParallelForDistributeInnerBoundParams(
2104 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2105 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2106 const auto &Dir = cast<OMPLoopDirective>(S);
2107 LValue LB =
2108 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002109 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002110 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2111 CapturedVars.push_back(LBCast);
2112 LValue UB =
2113 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2114
Alexey Bataevddf3db92018-04-13 17:31:06 +00002115 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2117 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002118}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002119
2120static void
2121emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2122 const OMPLoopDirective &S,
2123 CodeGenFunction::JumpDest LoopExit) {
2124 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002125 PrePostActionTy &Action) {
2126 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002127 bool HasCancel = false;
2128 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2129 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2130 HasCancel = D->hasCancel();
2131 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2132 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002133 else if (const auto *D =
2134 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2135 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002136 }
2137 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2138 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002139 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2140 emitDistributeParallelForInnerBounds,
2141 emitDistributeParallelForDispatchBounds);
2142 };
2143
2144 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002145 CGF, S,
2146 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2147 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002148 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002149}
2150
Carlo Bertolli9925f152016-06-27 14:55:37 +00002151void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2152 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002153 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2154 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2155 S.getDistInc());
2156 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002157 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002158 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002159}
2160
Kelvin Li4a39add2016-07-05 05:00:15 +00002161void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2162 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002163 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2164 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2165 S.getDistInc());
2166 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002167 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002168 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002169}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002170
2171void CodeGenFunction::EmitOMPDistributeSimdDirective(
2172 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002173 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2174 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2175 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002176 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002177 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002178}
2179
Alexey Bataevf8365372017-11-17 17:57:25 +00002180void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2181 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2182 // Emit SPMD target parallel for region as a standalone region.
2183 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2184 emitOMPSimdRegion(CGF, S, Action);
2185 };
2186 llvm::Function *Fn;
2187 llvm::Constant *Addr;
2188 // Emit target region as a standalone region.
2189 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2190 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2191 assert(Fn && Addr && "Target device function emission failed.");
2192}
2193
Kelvin Li986330c2016-07-20 22:57:10 +00002194void CodeGenFunction::EmitOMPTargetSimdDirective(
2195 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002196 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2197 emitOMPSimdRegion(CGF, S, Action);
2198 };
2199 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002200}
2201
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002202namespace {
2203 struct ScheduleKindModifiersTy {
2204 OpenMPScheduleClauseKind Kind;
2205 OpenMPScheduleClauseModifier M1;
2206 OpenMPScheduleClauseModifier M2;
2207 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2208 OpenMPScheduleClauseModifier M1,
2209 OpenMPScheduleClauseModifier M2)
2210 : Kind(Kind), M1(M1), M2(M2) {}
2211 };
2212} // namespace
2213
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002214bool CodeGenFunction::EmitOMPWorksharingLoop(
2215 const OMPLoopDirective &S, Expr *EUB,
2216 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2217 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002218 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002219 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2220 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002221 EmitVarDecl(*IVDecl);
2222
2223 // Emit the iterations count variable.
2224 // If it is not a variable, Sema decided to calculate iterations count on each
2225 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002226 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002227 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2228 // Emit calculation of the iterations count.
2229 EmitIgnoredExpr(S.getCalcLastIteration());
2230 }
2231
Alexey Bataevddf3db92018-04-13 17:31:06 +00002232 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002233
Alexey Bataev38e89532015-04-16 04:54:05 +00002234 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002235 // Check pre-condition.
2236 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002237 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002238 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002239 // If the condition constant folds and can be elided, avoid emitting the
2240 // whole loop.
2241 bool CondConstant;
2242 llvm::BasicBlock *ContBlock = nullptr;
2243 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2244 if (!CondConstant)
2245 return false;
2246 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002247 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002248 ContBlock = createBasicBlock("omp.precond.end");
2249 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002250 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002251 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002252 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002253 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002254
Alexey Bataevea33dee2018-02-15 23:39:43 +00002255 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002256 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002257 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002258 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002259 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002260 else
2261 Ordered = true;
2262 }
2263
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002264 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002265 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002266 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002267 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002268
2269 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2270 LValue LB = Bounds.first;
2271 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002272 LValue ST =
2273 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2274 LValue IL =
2275 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2276
Alexander Musmanc6388682014-12-15 07:07:06 +00002277 // Emit 'then' code.
2278 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002279 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002280 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002281 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002282 // initialization of firstprivate variables and post-update of
2283 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002284 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002285 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002286 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002287 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002288 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002289 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002290 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002291 EmitOMPPrivateLoopCounters(S, LoopScope);
2292 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002293 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002294 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2295 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002296
2297 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002298 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002299 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002300 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002301 ScheduleKind.Schedule = C->getScheduleKind();
2302 ScheduleKind.M1 = C->getFirstScheduleModifier();
2303 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002304 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002305 } else {
2306 // Default behaviour for schedule clause.
2307 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002308 *this, S, ScheduleKind.Schedule, ChunkExpr);
2309 }
2310 bool HasChunkSizeOne = false;
2311 llvm::Value *Chunk = nullptr;
2312 if (ChunkExpr) {
2313 Chunk = EmitScalarExpr(ChunkExpr);
2314 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2315 S.getIterationVariable()->getType(),
2316 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002317 Expr::EvalResult Result;
2318 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2319 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002320 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002321 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002322 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002323 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2324 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002325 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2326 // If the static schedule kind is specified or if the ordered clause is
2327 // specified, and if no monotonic modifier is specified, the effect will
2328 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002329 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2330 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2331 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2332 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2333 /* Chunked */ Chunk != nullptr) ||
2334 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002335 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002336 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2337 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002338 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2339 // When no chunk_size is specified, the iteration space is divided into
2340 // chunks that are approximately equal in size, and at most one chunk is
2341 // distributed to each thread. Note that the size of the chunks is
2342 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002343 CGOpenMPRuntime::StaticRTInput StaticInit(
2344 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002345 UB.getAddress(), ST.getAddress(),
2346 StaticChunkedOne ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002347 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002348 ScheduleKind, StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002349 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002350 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002351 // UB = min(UB, GlobalUB);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002352 if (!StaticChunkedOne)
2353 EmitIgnoredExpr(S.getEnsureUpperBound());
Alexander Musmanc6388682014-12-15 07:07:06 +00002354 // IV = LB;
2355 EmitIgnoredExpr(S.getInit());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002356 // For unchunked static schedule generate:
2357 //
2358 // while (idx <= UB) {
2359 // BODY;
2360 // ++idx;
2361 // }
2362 //
2363 // For static schedule with chunk one:
2364 //
2365 // while (IV <= PrevUB) {
2366 // BODY;
2367 // IV += ST;
2368 // }
2369 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
2370 StaticChunkedOne ? S.getCombinedParForInDistCond() : S.getCond(),
2371 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2372 [&S, LoopExit](CodeGenFunction &CGF) {
2373 CGF.EmitOMPLoopBody(S, LoopExit);
2374 CGF.EmitStopPoint(&S);
2375 },
2376 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002377 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002378 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002379 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002380 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002381 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002382 };
2383 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002384 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002385 const bool IsMonotonic =
2386 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2387 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2388 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2389 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002390 // Emit the outer loop, which requests its work chunk [LB..UB] from
2391 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002392 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2393 ST.getAddress(), IL.getAddress(),
2394 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002395 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002396 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002397 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002398 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002399 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2400 return CGF.Builder.CreateIsNotNull(
2401 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2402 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002403 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002404 EmitOMPReductionClauseFinal(
2405 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2406 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2407 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002408 // Emit post-update of the reduction variables if IsLastIter != 0.
2409 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002410 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002411 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002412 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002413 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002414 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2415 if (HasLastprivateClause)
2416 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002417 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002418 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002419 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002420 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002421 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002422 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002423 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002424 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002425 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002426 if (ContBlock) {
2427 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002428 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002429 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002430 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002431 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002432}
2433
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002434/// The following two functions generate expressions for the loop lower
2435/// and upper bounds in case of static and dynamic (dispatch) schedule
2436/// of the associated 'for' or 'distribute' loop.
2437static std::pair<LValue, LValue>
2438emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002439 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002440 LValue LB =
2441 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2442 LValue UB =
2443 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2444 return {LB, UB};
2445}
2446
2447/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2448/// consider the lower and upper bound expressions generated by the
2449/// worksharing loop support, but we use 0 and the iteration space size as
2450/// constants
2451static std::pair<llvm::Value *, llvm::Value *>
2452emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2453 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002454 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002455 const Expr *IVExpr = LS.getIterationVariable();
2456 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2457 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2458 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2459 return {LBVal, UBVal};
2460}
2461
Alexander Musmanc6388682014-12-15 07:07:06 +00002462void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002463 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2465 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002466 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002467 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2468 emitForLoopBounds,
2469 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002470 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002471 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002472 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002473 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2474 S.hasCancel());
2475 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002476
2477 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002478 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002479 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002480}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002481
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002482void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002483 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002484 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2485 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002486 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2487 emitForLoopBounds,
2488 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002489 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002490 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002491 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002492 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2493 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002494
2495 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002496 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002497 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002498}
2499
Alexey Bataev2df54a02015-03-12 08:53:29 +00002500static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2501 const Twine &Name,
2502 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002503 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002504 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002505 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002506 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002507}
2508
Alexey Bataev3392d762016-02-16 11:18:12 +00002509void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002510 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2511 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002512 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002513 auto &&CodeGen = [&S, CapturedStmt, CS,
2514 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2515 ASTContext &C = CGF.getContext();
2516 QualType KmpInt32Ty =
2517 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002518 // Emit helper vars inits.
2519 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2520 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002521 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2522 ? CGF.Builder.getInt32(CS->size() - 1)
2523 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002524 LValue UB =
2525 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2526 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2527 CGF.Builder.getInt32(1));
2528 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2529 CGF.Builder.getInt32(0));
2530 // Loop counter.
2531 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002532 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002533 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002534 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002535 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2536 // Generate condition for loop.
2537 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002538 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002539 // Increment for loop counter.
2540 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002541 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002542 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002543 // Iterate through all sections and emit a switch construct:
2544 // switch (IV) {
2545 // case 0:
2546 // <SectionStmt[0]>;
2547 // break;
2548 // ...
2549 // case <NumSection> - 1:
2550 // <SectionStmt[<NumSection> - 1]>;
2551 // break;
2552 // }
2553 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002554 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2555 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002556 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002557 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002558 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002559 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002560 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002561 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2562 CGF.EmitBlock(CaseBB);
2563 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002564 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002565 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002566 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002567 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002568 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002569 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002570 CGF.EmitBlock(CaseBB);
2571 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002572 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002573 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002574 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002575 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002576 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002577
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002578 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2579 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002580 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002581 // initialization of firstprivate variables and post-update of lastprivate
2582 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002583 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002584 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002585 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002586 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002587 CGF.EmitOMPPrivateClause(S, LoopScope);
2588 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2589 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2590 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002591 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2592 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002593
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002594 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002595 OpenMPScheduleTy ScheduleKind;
2596 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002597 CGOpenMPRuntime::StaticRTInput StaticInit(
2598 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2599 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002600 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002601 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002602 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002603 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002604 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002605 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2606 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2607 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002608 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002609 // while (idx <= UB) { BODY; ++idx; }
2610 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2611 [](CodeGenFunction &) {});
2612 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002613 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002614 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002615 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002616 };
2617 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002618 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002619 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002620 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2621 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002622 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002623 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002624
2625 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2626 if (HasLastprivates)
2627 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002628 S, /*NoFinals=*/false,
2629 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002630 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002631 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002632
2633 bool HasCancel = false;
2634 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2635 HasCancel = OSD->hasCancel();
2636 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2637 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002638 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002639 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2640 HasCancel);
2641 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2642 // clause. Otherwise the barrier will be generated by the codegen for the
2643 // directive.
2644 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002645 // Emit implicit barrier to synchronize threads and avoid data races on
2646 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002647 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002648 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002649 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002650}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002651
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002652void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002653 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002654 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002655 EmitSections(S);
2656 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002657 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002658 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002659 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002660 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002661 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002662}
2663
2664void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002665 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002666 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002667 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002668 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002669 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2670 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002671}
2672
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002673void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002674 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002675 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002676 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002677 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002678 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002679 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 // Build a list of copyprivate variables along with helper expressions
2681 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002682 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002683 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002684 DestExprs.append(C->destination_exprs().begin(),
2685 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002686 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002687 AssignmentOps.append(C->assignment_ops().begin(),
2688 C->assignment_ops().end());
2689 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002690 // Emit code for 'single' region along with 'copyprivate' clauses
2691 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2692 Action.Enter(CGF);
2693 OMPPrivateScope SingleScope(CGF);
2694 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2695 CGF.EmitOMPPrivateClause(S, SingleScope);
2696 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002697 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002698 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002699 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002700 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002701 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002702 CopyprivateVars, DestExprs,
2703 SrcExprs, AssignmentOps);
2704 }
2705 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2706 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002707 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002708 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002710 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002711 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002712}
2713
Alexey Bataev8d690652014-12-04 07:23:53 +00002714void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002715 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2716 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002717 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002718 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002719 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002720 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002721}
2722
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002723void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002724 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2725 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002726 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002727 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002728 const Expr *Hint = nullptr;
2729 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002730 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002731 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002732 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2733 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002734 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002735}
2736
Alexey Bataev671605e2015-04-13 05:28:11 +00002737void CodeGenFunction::EmitOMPParallelForDirective(
2738 const OMPParallelForDirective &S) {
2739 // Emit directive as a combined directive that consists of two implicit
2740 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002741 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2742 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002743 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002744 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2745 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002746 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002747 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2748 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002749}
2750
Alexander Musmane4e893b2014-09-23 09:33:00 +00002751void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002752 const OMPParallelForSimdDirective &S) {
2753 // Emit directive as a combined directive that consists of two implicit
2754 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002755 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2756 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002757 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2758 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002759 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002760 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2761 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002762}
2763
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002764void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002765 const OMPParallelSectionsDirective &S) {
2766 // Emit directive as a combined directive that consists of two implicit
2767 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002768 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2769 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002770 CGF.EmitSections(S);
2771 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002772 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2773 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002774}
2775
Alexey Bataev475a7442018-01-12 19:39:11 +00002776void CodeGenFunction::EmitOMPTaskBasedDirective(
2777 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2778 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2779 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002780 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002781 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002782 auto I = CS->getCapturedDecl()->param_begin();
2783 auto PartId = std::next(I);
2784 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002785 // Check if the task is final
2786 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2787 // If the condition constant folds and can be elided, try to avoid emitting
2788 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002789 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002790 bool CondConstant;
2791 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2792 Data.Final.setInt(CondConstant);
2793 else
2794 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2795 } else {
2796 // By default the task is not final.
2797 Data.Final.setInt(/*IntVal=*/false);
2798 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002799 // Check if the task has 'priority' clause.
2800 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002801 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002802 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002803 Data.Priority.setPointer(EmitScalarConversion(
2804 EmitScalarExpr(Prio), Prio->getType(),
2805 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2806 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002807 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002808 // The first function argument for tasks is a thread id, the second one is a
2809 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002810 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2811 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002812 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002813 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002814 for (const Expr *IInit : C->private_copies()) {
2815 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002816 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002817 Data.PrivateVars.push_back(*IRef);
2818 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002819 }
2820 ++IRef;
2821 }
2822 }
2823 EmittedAsPrivate.clear();
2824 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002825 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002826 auto IRef = C->varlist_begin();
2827 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002828 for (const Expr *IInit : C->private_copies()) {
2829 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002830 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002831 Data.FirstprivateVars.push_back(*IRef);
2832 Data.FirstprivateCopies.push_back(IInit);
2833 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002834 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002835 ++IRef;
2836 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002837 }
2838 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002839 // Get list of lastprivate variables (for taskloops).
2840 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2841 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2842 auto IRef = C->varlist_begin();
2843 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002844 for (const Expr *IInit : C->private_copies()) {
2845 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002846 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2847 Data.LastprivateVars.push_back(*IRef);
2848 Data.LastprivateCopies.push_back(IInit);
2849 }
2850 LastprivateDstsOrigs.insert(
2851 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2852 cast<DeclRefExpr>(*IRef)});
2853 ++IRef;
2854 ++ID;
2855 }
2856 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002857 SmallVector<const Expr *, 4> LHSs;
2858 SmallVector<const Expr *, 4> RHSs;
2859 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2860 auto IPriv = C->privates().begin();
2861 auto IRed = C->reduction_ops().begin();
2862 auto ILHS = C->lhs_exprs().begin();
2863 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002864 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002865 Data.ReductionVars.emplace_back(Ref);
2866 Data.ReductionCopies.emplace_back(*IPriv);
2867 Data.ReductionOps.emplace_back(*IRed);
2868 LHSs.emplace_back(*ILHS);
2869 RHSs.emplace_back(*IRHS);
2870 std::advance(IPriv, 1);
2871 std::advance(IRed, 1);
2872 std::advance(ILHS, 1);
2873 std::advance(IRHS, 1);
2874 }
2875 }
2876 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002877 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002878 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002879 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00002880 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00002881 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00002882 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2883 CapturedRegion](CodeGenFunction &CGF,
2884 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002885 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002886 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002887 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2888 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00002889 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
2890 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00002891 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002892 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
2893 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
2894 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
2895 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00002896 // Map privates.
2897 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2898 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2899 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002900 for (const Expr *E : Data.PrivateVars) {
2901 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002902 Address PrivatePtr = CGF.CreateMemTemp(
2903 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002904 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002905 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002906 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002907 for (const Expr *E : Data.FirstprivateVars) {
2908 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 Address PrivatePtr =
2910 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2911 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002912 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002913 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002914 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002915 for (const Expr *E : Data.LastprivateVars) {
2916 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002917 Address PrivatePtr =
2918 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2919 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002920 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002921 CallArgs.push_back(PrivatePtr.getPointer());
2922 }
James Y Knight9871db02019-02-05 16:42:33 +00002923 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2924 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002925 for (const auto &Pair : LastprivateDstsOrigs) {
2926 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002927 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
2928 /*RefersToEnclosingVariableOrCapture=*/
2929 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
2930 Pair.second->getType(), VK_LValue,
2931 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002932 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2933 return CGF.EmitLValue(&DRE).getAddress();
2934 });
2935 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002936 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002937 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2938 CGF.getContext().getDeclAlign(Pair.first));
2939 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2940 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002941 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002942 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002943 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002944 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2945 Data.ReductionOps);
2946 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2947 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2948 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2949 RedCG.emitSharedLValue(CGF, Cnt);
2950 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002951 // FIXME: This must removed once the runtime library is fixed.
2952 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002953 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002954 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002955 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002956 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002957 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002958 Replacement =
2959 Address(CGF.EmitScalarConversion(
2960 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2961 CGF.getContext().getPointerType(
2962 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002963 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002964 Replacement.getAlignment());
2965 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2966 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2967 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002968 }
2969 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002970 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002971 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002972 SmallVector<const Expr *, 4> InRedVars;
2973 SmallVector<const Expr *, 4> InRedPrivs;
2974 SmallVector<const Expr *, 4> InRedOps;
2975 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2976 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2977 auto IPriv = C->privates().begin();
2978 auto IRed = C->reduction_ops().begin();
2979 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002980 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002981 InRedVars.emplace_back(Ref);
2982 InRedPrivs.emplace_back(*IPriv);
2983 InRedOps.emplace_back(*IRed);
2984 TaskgroupDescriptors.emplace_back(*ITD);
2985 std::advance(IPriv, 1);
2986 std::advance(IRed, 1);
2987 std::advance(ITD, 1);
2988 }
2989 }
2990 // Privatize in_reduction items here, because taskgroup descriptors must be
2991 // privatized earlier.
2992 OMPPrivateScope InRedScope(CGF);
2993 if (!InRedVars.empty()) {
2994 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2995 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2996 RedCG.emitSharedLValue(CGF, Cnt);
2997 RedCG.emitAggregateType(CGF, Cnt);
2998 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002999 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003000 // FIXME: This must removed once the runtime library is fixed.
3001 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003002 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003003 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003004 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003005 llvm::Value *ReductionsPtr =
3006 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3007 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003008 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003009 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003010 Replacement = Address(
3011 CGF.EmitScalarConversion(
3012 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3013 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003014 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003015 Replacement.getAlignment());
3016 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3017 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3018 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003019 }
3020 }
3021 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003022
3023 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003024 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003025 };
James Y Knight9871db02019-02-05 16:42:33 +00003026 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003027 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3028 Data.NumberOfParts);
3029 OMPLexicalScope Scope(*this, S);
3030 TaskGen(*this, OutlinedFn, Data);
3031}
3032
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003033static ImplicitParamDecl *
3034createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003035 QualType Ty, CapturedDecl *CD,
3036 SourceLocation Loc) {
3037 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3038 ImplicitParamDecl::Other);
3039 auto *OrigRef = DeclRefExpr::Create(
3040 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3041 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3042 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3043 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003044 auto *PrivateRef = DeclRefExpr::Create(
3045 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003046 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003047 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003048 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3049 ImplicitParamDecl::Other);
3050 auto *InitRef = DeclRefExpr::Create(
3051 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3052 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003053 PrivateVD->setInitStyle(VarDecl::CInit);
3054 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3055 InitRef, /*BasePath=*/nullptr,
3056 VK_RValue));
3057 Data.FirstprivateVars.emplace_back(OrigRef);
3058 Data.FirstprivateCopies.emplace_back(PrivateRef);
3059 Data.FirstprivateInits.emplace_back(InitRef);
3060 return OrigVD;
3061}
3062
3063void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3064 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3065 OMPTargetDataInfo &InputInfo) {
3066 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003067 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3068 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3069 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3070 auto I = CS->getCapturedDecl()->param_begin();
3071 auto PartId = std::next(I);
3072 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003073 OMPTaskDataTy Data;
3074 // The task is not final.
3075 Data.Final.setInt(/*IntVal=*/false);
3076 // Get list of firstprivate variables.
3077 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3078 auto IRef = C->varlist_begin();
3079 auto IElemInitRef = C->inits().begin();
3080 for (auto *IInit : C->private_copies()) {
3081 Data.FirstprivateVars.push_back(*IRef);
3082 Data.FirstprivateCopies.push_back(IInit);
3083 Data.FirstprivateInits.push_back(*IElemInitRef);
3084 ++IRef;
3085 ++IElemInitRef;
3086 }
3087 }
3088 OMPPrivateScope TargetScope(*this);
3089 VarDecl *BPVD = nullptr;
3090 VarDecl *PVD = nullptr;
3091 VarDecl *SVD = nullptr;
3092 if (InputInfo.NumberOfTargetItems > 0) {
3093 auto *CD = CapturedDecl::Create(
3094 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3095 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3096 QualType BaseAndPointersType = getContext().getConstantArrayType(
3097 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3098 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003099 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003100 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003101 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003102 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003103 QualType SizesType = getContext().getConstantArrayType(
3104 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3105 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003106 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003107 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003108 TargetScope.addPrivate(
3109 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3110 TargetScope.addPrivate(PVD,
3111 [&InputInfo]() { return InputInfo.PointersArray; });
3112 TargetScope.addPrivate(SVD,
3113 [&InputInfo]() { return InputInfo.SizesArray; });
3114 }
3115 (void)TargetScope.Privatize();
3116 // Build list of dependences.
3117 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003118 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003119 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003120 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3121 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3122 // Set proper addresses for generated private copies.
3123 OMPPrivateScope Scope(CGF);
3124 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003125 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3126 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003127 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003128 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3129 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3130 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3131 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003132 // Map privates.
3133 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3134 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3135 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003136 for (const Expr *E : Data.FirstprivateVars) {
3137 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003138 Address PrivatePtr =
3139 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3140 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003141 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003142 CallArgs.push_back(PrivatePtr.getPointer());
3143 }
James Y Knight9871db02019-02-05 16:42:33 +00003144 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3145 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003146 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003147 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3148 CGF.getContext().getDeclAlign(Pair.first));
3149 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3150 }
3151 }
3152 // Privatize all private variables except for in_reduction items.
3153 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003154 if (InputInfo.NumberOfTargetItems > 0) {
3155 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003156 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003157 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003158 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003159 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003160 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003161 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003162
3163 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003164 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003165 BodyGen(CGF);
3166 };
James Y Knight9871db02019-02-05 16:42:33 +00003167 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003168 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3169 Data.NumberOfParts);
3170 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3171 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3172 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3173 SourceLocation());
3174
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003175 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003176 SharedsTy, CapturedStruct, &IfCond, Data);
3177}
3178
Alexey Bataev7292c292016-04-25 12:22:29 +00003179void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3180 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003181 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003182 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3183 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003184 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003185 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3186 if (C->getNameModifier() == OMPD_unknown ||
3187 C->getNameModifier() == OMPD_task) {
3188 IfCond = C->getCondition();
3189 break;
3190 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003191 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003192
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003193 OMPTaskDataTy Data;
3194 // Check if we should emit tied or untied task.
3195 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003196 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3197 CGF.EmitStmt(CS->getCapturedStmt());
3198 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003199 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003200 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003201 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003202 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003203 SharedsTy, CapturedStruct, IfCond,
3204 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003205 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003206 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003207}
3208
Alexey Bataev9f797f32015-02-05 05:57:51 +00003209void CodeGenFunction::EmitOMPTaskyieldDirective(
3210 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003211 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003212}
3213
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003214void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003215 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003216}
3217
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003218void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003219 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003220}
3221
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003222void CodeGenFunction::EmitOMPTaskgroupDirective(
3223 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003224 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3225 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003226 if (const Expr *E = S.getReductionRef()) {
3227 SmallVector<const Expr *, 4> LHSs;
3228 SmallVector<const Expr *, 4> RHSs;
3229 OMPTaskDataTy Data;
3230 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3231 auto IPriv = C->privates().begin();
3232 auto IRed = C->reduction_ops().begin();
3233 auto ILHS = C->lhs_exprs().begin();
3234 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003235 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003236 Data.ReductionVars.emplace_back(Ref);
3237 Data.ReductionCopies.emplace_back(*IPriv);
3238 Data.ReductionOps.emplace_back(*IRed);
3239 LHSs.emplace_back(*ILHS);
3240 RHSs.emplace_back(*IRHS);
3241 std::advance(IPriv, 1);
3242 std::advance(IRed, 1);
3243 std::advance(ILHS, 1);
3244 std::advance(IRHS, 1);
3245 }
3246 }
3247 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003248 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003249 LHSs, RHSs, Data);
3250 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3251 CGF.EmitVarDecl(*VD);
3252 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3253 /*Volatile=*/false, E->getType());
3254 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003255 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003256 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003257 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003258 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003259}
3260
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003261void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003262 CGM.getOpenMPRuntime().emitFlush(
3263 *this,
3264 [&S]() -> ArrayRef<const Expr *> {
3265 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3266 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3267 FlushClause->varlist_end());
3268 return llvm::None;
3269 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003270 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003271}
3272
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003273void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3274 const CodeGenLoopTy &CodeGenLoop,
3275 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003276 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003277 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3278 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003279 EmitVarDecl(*IVDecl);
3280
3281 // Emit the iterations count variable.
3282 // If it is not a variable, Sema decided to calculate iterations count on each
3283 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003284 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003285 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3286 // Emit calculation of the iterations count.
3287 EmitIgnoredExpr(S.getCalcLastIteration());
3288 }
3289
Alexey Bataevddf3db92018-04-13 17:31:06 +00003290 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003291
Carlo Bertolli962bb802017-01-03 18:24:42 +00003292 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003293 // Check pre-condition.
3294 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003295 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003296 // Skip the entire loop if we don't meet the precondition.
3297 // If the condition constant folds and can be elided, avoid emitting the
3298 // whole loop.
3299 bool CondConstant;
3300 llvm::BasicBlock *ContBlock = nullptr;
3301 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3302 if (!CondConstant)
3303 return;
3304 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003305 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003306 ContBlock = createBasicBlock("omp.precond.end");
3307 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3308 getProfileCount(&S));
3309 EmitBlock(ThenBlock);
3310 incrementProfileCounter(&S);
3311 }
3312
Alexey Bataev617db5f2017-12-04 15:38:33 +00003313 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003314 // Emit 'then' code.
3315 {
3316 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003317
3318 LValue LB = EmitOMPHelperVar(
3319 *this, cast<DeclRefExpr>(
3320 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3321 ? S.getCombinedLowerBoundVariable()
3322 : S.getLowerBoundVariable())));
3323 LValue UB = EmitOMPHelperVar(
3324 *this, cast<DeclRefExpr>(
3325 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3326 ? S.getCombinedUpperBoundVariable()
3327 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003328 LValue ST =
3329 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3330 LValue IL =
3331 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3332
3333 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003334 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003335 // Emit implicit barrier to synchronize threads and avoid data races
3336 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003337 // lastprivate variables.
3338 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003339 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003340 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003341 }
3342 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003343 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003344 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3345 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003346 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003347 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003348 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003349 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003350 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3351 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003352
3353 // Detect the distribute schedule kind and chunk.
3354 llvm::Value *Chunk = nullptr;
3355 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003356 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003357 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003358 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003359 Chunk = EmitScalarExpr(Ch);
3360 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003361 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003362 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003363 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003364 } else {
3365 // Default behaviour for dist_schedule clause.
3366 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3367 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003368 }
3369 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3370 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3371
3372 // OpenMP [2.10.8, distribute Construct, Description]
3373 // If dist_schedule is specified, kind must be static. If specified,
3374 // iterations are divided into chunks of size chunk_size, chunks are
3375 // assigned to the teams of the league in a round-robin fashion in the
3376 // order of the team number. When no chunk_size is specified, the
3377 // iteration space is divided into chunks that are approximately equal
3378 // in size, and at most one chunk is distributed to each team of the
3379 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003380 bool StaticChunked = RT.isStaticChunked(
3381 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3382 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003383 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003384 /* Chunked */ Chunk != nullptr) ||
3385 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003386 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3387 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003388 CGOpenMPRuntime::StaticRTInput StaticInit(
3389 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003390 LB.getAddress(), UB.getAddress(), ST.getAddress(),
3391 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003392 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003393 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003394 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003395 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3396 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003397 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3398 ? S.getCombinedEnsureUpperBound()
3399 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003400 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003401 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3402 ? S.getCombinedInit()
3403 : S.getInit());
3404
Alexey Bataevddf3db92018-04-13 17:31:06 +00003405 const Expr *Cond =
3406 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3407 ? S.getCombinedCond()
3408 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003409
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003410 if (StaticChunked)
3411 Cond = S.getCombinedDistCond();
3412
3413 // For static unchunked schedules generate:
3414 //
3415 // 1. For distribute alone, codegen
3416 // while (idx <= UB) {
3417 // BODY;
3418 // ++idx;
3419 // }
3420 //
3421 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3422 // while (idx <= UB) {
3423 // <CodeGen rest of pragma>(LB, UB);
3424 // idx += ST;
3425 // }
3426 //
3427 // For static chunk one schedule generate:
3428 //
3429 // while (IV <= GlobalUB) {
3430 // <CodeGen rest of pragma>(LB, UB);
3431 // LB += ST;
3432 // UB += ST;
3433 // UB = min(UB, GlobalUB);
3434 // IV = LB;
3435 // }
3436 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003437 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3438 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3439 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003440 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003441 [&S, StaticChunked](CodeGenFunction &CGF) {
3442 if (StaticChunked) {
3443 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3444 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3445 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3446 CGF.EmitIgnoredExpr(S.getCombinedInit());
3447 }
3448 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003449 EmitBlock(LoopExit.getBlock());
3450 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003451 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003452 } else {
3453 // Emit the outer loop, which requests its work chunk [LB..UB] from
3454 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003455 const OMPLoopArguments LoopArguments = {
3456 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3457 Chunk};
3458 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3459 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003460 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003461 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003462 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003463 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003464 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003465 });
3466 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003467 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3468 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3469 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003470 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003471 // Emit post-update of the reduction variables if IsLastIter != 0.
3472 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003473 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003474 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003475 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003476 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003477 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003478 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003479 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003480 EmitOMPLastprivateClauseFinal(
3481 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003482 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003483 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003484 }
3485
3486 // We're now done with the loop, so jump to the continuation block.
3487 if (ContBlock) {
3488 EmitBranch(ContBlock);
3489 EmitBlock(ContBlock, true);
3490 }
3491 }
3492}
3493
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003494void CodeGenFunction::EmitOMPDistributeDirective(
3495 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003496 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003497 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003498 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003499 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003500 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003501}
3502
Alexey Bataev5f600d62015-09-29 03:48:57 +00003503static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3504 const CapturedStmt *S) {
3505 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3506 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3507 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003508 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003509 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003510 return Fn;
3511}
3512
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003513void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003514 if (S.hasClausesOfKind<OMPDependClause>()) {
3515 assert(!S.getAssociatedStmt() &&
3516 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003517 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3518 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003519 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003520 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003521 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003522 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3523 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003524 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003525 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003526 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3527 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003528 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003529 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003530 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003531 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003532 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003533 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003534 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003535 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003536 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003537 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003538}
3539
Alexey Bataevb57056f2015-01-22 06:17:56 +00003540static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003541 QualType SrcType, QualType DestType,
3542 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003543 assert(CGF.hasScalarEvaluationKind(DestType) &&
3544 "DestType must have scalar evaluation kind.");
3545 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003546 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3547 DestType, Loc)
3548 : CGF.EmitComplexToScalarConversion(
3549 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003550}
3551
3552static CodeGenFunction::ComplexPairTy
3553convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003554 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003555 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3556 "DestType must have complex evaluation kind.");
3557 CodeGenFunction::ComplexPairTy ComplexVal;
3558 if (Val.isScalar()) {
3559 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003560 QualType DestElementType =
3561 DestType->castAs<ComplexType>()->getElementType();
3562 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3563 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003564 ComplexVal = CodeGenFunction::ComplexPairTy(
3565 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3566 } else {
3567 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003568 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3569 QualType DestElementType =
3570 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003571 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003572 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003573 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003574 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003575 }
3576 return ComplexVal;
3577}
3578
Alexey Bataev5e018f92015-04-23 06:35:10 +00003579static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3580 LValue LVal, RValue RVal) {
3581 if (LVal.isGlobalReg()) {
3582 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3583 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003584 CGF.EmitAtomicStore(RVal, LVal,
3585 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3586 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003587 LVal.isVolatile(), /*IsInit=*/false);
3588 }
3589}
3590
Alexey Bataev8524d152016-01-21 12:35:58 +00003591void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3592 QualType RValTy, SourceLocation Loc) {
3593 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003594 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003595 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3596 *this, RVal, RValTy, LVal.getType(), Loc)),
3597 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003598 break;
3599 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003600 EmitStoreOfComplex(
3601 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003602 /*isInit=*/false);
3603 break;
3604 case TEK_Aggregate:
3605 llvm_unreachable("Must be a scalar or complex.");
3606 }
3607}
3608
Alexey Bataevddf3db92018-04-13 17:31:06 +00003609static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003610 const Expr *X, const Expr *V,
3611 SourceLocation Loc) {
3612 // v = x;
3613 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3614 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3615 LValue XLValue = CGF.EmitLValue(X);
3616 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003617 RValue Res = XLValue.isGlobalReg()
3618 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003619 : CGF.EmitAtomicLoad(
3620 XLValue, Loc,
3621 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3622 : llvm::AtomicOrdering::Monotonic,
3623 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003624 // OpenMP, 2.12.6, atomic Construct
3625 // Any atomic construct with a seq_cst clause forces the atomically
3626 // performed operation to include an implicit flush operation without a
3627 // list.
3628 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003629 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003630 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003631}
3632
Alexey Bataevddf3db92018-04-13 17:31:06 +00003633static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003634 const Expr *X, const Expr *E,
3635 SourceLocation Loc) {
3636 // x = expr;
3637 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003638 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003639 // OpenMP, 2.12.6, atomic Construct
3640 // Any atomic construct with a seq_cst clause forces the atomically
3641 // performed operation to include an implicit flush operation without a
3642 // list.
3643 if (IsSeqCst)
3644 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3645}
3646
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003647static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3648 RValue Update,
3649 BinaryOperatorKind BO,
3650 llvm::AtomicOrdering AO,
3651 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003652 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003653 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003654 // expression is simple and atomic is allowed for the given type for the
3655 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003656 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003657 !Update.getScalarVal()->getType()->isIntegerTy() ||
3658 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3659 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003660 X.getAddress().getElementType())) ||
3661 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003662 !Context.getTargetInfo().hasBuiltinAtomic(
3663 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003664 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003665
3666 llvm::AtomicRMWInst::BinOp RMWOp;
3667 switch (BO) {
3668 case BO_Add:
3669 RMWOp = llvm::AtomicRMWInst::Add;
3670 break;
3671 case BO_Sub:
3672 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003673 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003674 RMWOp = llvm::AtomicRMWInst::Sub;
3675 break;
3676 case BO_And:
3677 RMWOp = llvm::AtomicRMWInst::And;
3678 break;
3679 case BO_Or:
3680 RMWOp = llvm::AtomicRMWInst::Or;
3681 break;
3682 case BO_Xor:
3683 RMWOp = llvm::AtomicRMWInst::Xor;
3684 break;
3685 case BO_LT:
3686 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3687 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3688 : llvm::AtomicRMWInst::Max)
3689 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3690 : llvm::AtomicRMWInst::UMax);
3691 break;
3692 case BO_GT:
3693 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3694 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3695 : llvm::AtomicRMWInst::Min)
3696 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3697 : llvm::AtomicRMWInst::UMin);
3698 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003699 case BO_Assign:
3700 RMWOp = llvm::AtomicRMWInst::Xchg;
3701 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003702 case BO_Mul:
3703 case BO_Div:
3704 case BO_Rem:
3705 case BO_Shl:
3706 case BO_Shr:
3707 case BO_LAnd:
3708 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003709 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003710 case BO_PtrMemD:
3711 case BO_PtrMemI:
3712 case BO_LE:
3713 case BO_GE:
3714 case BO_EQ:
3715 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003716 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003717 case BO_AddAssign:
3718 case BO_SubAssign:
3719 case BO_AndAssign:
3720 case BO_OrAssign:
3721 case BO_XorAssign:
3722 case BO_MulAssign:
3723 case BO_DivAssign:
3724 case BO_RemAssign:
3725 case BO_ShlAssign:
3726 case BO_ShrAssign:
3727 case BO_Comma:
3728 llvm_unreachable("Unsupported atomic update operation");
3729 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003730 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003731 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3732 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003733 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003734 X.getType()->hasSignedIntegerRepresentation());
3735 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003736 llvm::Value *Res =
3737 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003738 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003739}
3740
Alexey Bataev5e018f92015-04-23 06:35:10 +00003741std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003742 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3743 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003744 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003745 // Update expressions are allowed to have the following forms:
3746 // x binop= expr; -> xrval + expr;
3747 // x++, ++x -> xrval + 1;
3748 // x--, --x -> xrval - 1;
3749 // x = x binop expr; -> xrval binop expr
3750 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003751 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3752 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003753 if (X.isGlobalReg()) {
3754 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3755 // 'xrval'.
3756 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3757 } else {
3758 // Perform compare-and-swap procedure.
3759 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003760 }
3761 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003762 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003763}
3764
Alexey Bataevddf3db92018-04-13 17:31:06 +00003765static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003766 const Expr *X, const Expr *E,
3767 const Expr *UE, bool IsXLHSInRHSPart,
3768 SourceLocation Loc) {
3769 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3770 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003771 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003772 // Update expressions are allowed to have the following forms:
3773 // x binop= expr; -> xrval + expr;
3774 // x++, ++x -> xrval + 1;
3775 // x--, --x -> xrval - 1;
3776 // x = x binop expr; -> xrval binop expr
3777 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003778 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003779 LValue XLValue = CGF.EmitLValue(X);
3780 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003781 llvm::AtomicOrdering AO = IsSeqCst
3782 ? llvm::AtomicOrdering::SequentiallyConsistent
3783 : llvm::AtomicOrdering::Monotonic;
3784 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3785 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3786 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3787 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3788 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3789 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3790 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3791 return CGF.EmitAnyExpr(UE);
3792 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003793 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3794 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3795 // OpenMP, 2.12.6, atomic Construct
3796 // Any atomic construct with a seq_cst clause forces the atomically
3797 // performed operation to include an implicit flush operation without a
3798 // list.
3799 if (IsSeqCst)
3800 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3801}
3802
3803static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003804 QualType SourceType, QualType ResType,
3805 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003806 switch (CGF.getEvaluationKind(ResType)) {
3807 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003808 return RValue::get(
3809 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003810 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003811 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003812 return RValue::getComplex(Res.first, Res.second);
3813 }
3814 case TEK_Aggregate:
3815 break;
3816 }
3817 llvm_unreachable("Must be a scalar or complex.");
3818}
3819
Alexey Bataevddf3db92018-04-13 17:31:06 +00003820static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003821 bool IsPostfixUpdate, const Expr *V,
3822 const Expr *X, const Expr *E,
3823 const Expr *UE, bool IsXLHSInRHSPart,
3824 SourceLocation Loc) {
3825 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3826 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3827 RValue NewVVal;
3828 LValue VLValue = CGF.EmitLValue(V);
3829 LValue XLValue = CGF.EmitLValue(X);
3830 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003831 llvm::AtomicOrdering AO = IsSeqCst
3832 ? llvm::AtomicOrdering::SequentiallyConsistent
3833 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003834 QualType NewVValType;
3835 if (UE) {
3836 // 'x' is updated with some additional value.
3837 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3838 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003839 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00003840 // Update expressions are allowed to have the following forms:
3841 // x binop= expr; -> xrval + expr;
3842 // x++, ++x -> xrval + 1;
3843 // x--, --x -> xrval - 1;
3844 // x = x binop expr; -> xrval binop expr
3845 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003846 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3847 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3848 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003849 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003850 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003851 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003852 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003853 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3854 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3855 RValue Res = CGF.EmitAnyExpr(UE);
3856 NewVVal = IsPostfixUpdate ? XRValue : Res;
3857 return Res;
3858 };
3859 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3860 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3861 if (Res.first) {
3862 // 'atomicrmw' instruction was generated.
3863 if (IsPostfixUpdate) {
3864 // Use old value from 'atomicrmw'.
3865 NewVVal = Res.second;
3866 } else {
3867 // 'atomicrmw' does not provide new value, so evaluate it using old
3868 // value of 'x'.
3869 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3870 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3871 NewVVal = CGF.EmitAnyExpr(UE);
3872 }
3873 }
3874 } else {
3875 // 'x' is simply rewritten with some 'expr'.
3876 NewVValType = X->getType().getNonReferenceType();
3877 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003878 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003879 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003880 NewVVal = XRValue;
3881 return ExprRValue;
3882 };
3883 // Try to perform atomicrmw xchg, otherwise simple exchange.
3884 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3885 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3886 Loc, Gen);
3887 if (Res.first) {
3888 // 'atomicrmw' instruction was generated.
3889 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3890 }
3891 }
3892 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003893 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003894 // OpenMP, 2.12.6, atomic Construct
3895 // Any atomic construct with a seq_cst clause forces the atomically
3896 // performed operation to include an implicit flush operation without a
3897 // list.
3898 if (IsSeqCst)
3899 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3900}
3901
Alexey Bataevddf3db92018-04-13 17:31:06 +00003902static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003903 bool IsSeqCst, bool IsPostfixUpdate,
3904 const Expr *X, const Expr *V, const Expr *E,
3905 const Expr *UE, bool IsXLHSInRHSPart,
3906 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003907 switch (Kind) {
3908 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003909 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003910 break;
3911 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003912 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00003913 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003914 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003915 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003916 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003917 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003918 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003919 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003920 IsXLHSInRHSPart, Loc);
3921 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003922 case OMPC_if:
3923 case OMPC_final:
3924 case OMPC_num_threads:
3925 case OMPC_private:
3926 case OMPC_firstprivate:
3927 case OMPC_lastprivate:
3928 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003929 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003930 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003931 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003932 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00003933 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00003934 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003935 case OMPC_collapse:
3936 case OMPC_default:
3937 case OMPC_seq_cst:
3938 case OMPC_shared:
3939 case OMPC_linear:
3940 case OMPC_aligned:
3941 case OMPC_copyin:
3942 case OMPC_copyprivate:
3943 case OMPC_flush:
3944 case OMPC_proc_bind:
3945 case OMPC_schedule:
3946 case OMPC_ordered:
3947 case OMPC_nowait:
3948 case OMPC_untied:
3949 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003950 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003951 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003952 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003953 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003954 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003955 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003956 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003957 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003958 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003959 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003960 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003961 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003962 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003963 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003964 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003965 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003966 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003967 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003968 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003969 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00003970 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00003971 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00003972 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00003973 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00003974 case OMPC_atomic_default_mem_order:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003975 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3976 }
3977}
3978
3979void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003980 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003981 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003982 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003983 // Find first clause (skip seq_cst clause, if it is first).
3984 if (C->getClauseKind() != OMPC_seq_cst) {
3985 Kind = C->getClauseKind();
3986 break;
3987 }
3988 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003989
Alexey Bataevddf3db92018-04-13 17:31:06 +00003990 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00003991 if (const auto *FE = dyn_cast<FullExpr>(CS))
3992 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003993 // Processing for statements under 'atomic capture'.
3994 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003995 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00003996 if (const auto *FE = dyn_cast<FullExpr>(C))
3997 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003998 }
3999 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004000
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004001 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4002 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004003 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004004 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004005 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004006 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004007 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004008 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004009 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004010}
4011
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004012static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4013 const OMPExecutableDirective &S,
4014 const RegionCodeGenTy &CodeGen) {
4015 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4016 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004017
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004018 // On device emit this construct as inlined code.
4019 if (CGM.getLangOpts().OpenMPIsDevice) {
4020 OMPLexicalScope Scope(CGF, S, OMPD_target);
4021 CGM.getOpenMPRuntime().emitInlinedDirective(
4022 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004023 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004024 });
4025 return;
4026 }
4027
Samuel Antaoee8fb302016-01-06 13:42:12 +00004028 llvm::Function *Fn = nullptr;
4029 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004030
Samuel Antaobed3c462015-10-02 16:14:20 +00004031 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004032 // Check for the at most one if clause associated with the target region.
4033 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4034 if (C->getNameModifier() == OMPD_unknown ||
4035 C->getNameModifier() == OMPD_target) {
4036 IfCond = C->getCondition();
4037 break;
4038 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004039 }
4040
4041 // Check if we have any device clause associated with the directive.
4042 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004043 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004044 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004045
Samuel Antaoee8fb302016-01-06 13:42:12 +00004046 // Check if we have an if clause whose conditional always evaluates to false
4047 // or if we do not have any targets specified. If so the target region is not
4048 // an offload entry point.
4049 bool IsOffloadEntry = true;
4050 if (IfCond) {
4051 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004052 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004053 IsOffloadEntry = false;
4054 }
4055 if (CGM.getLangOpts().OMPTargetTriples.empty())
4056 IsOffloadEntry = false;
4057
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004058 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004059 StringRef ParentName;
4060 // In case we have Ctors/Dtors we use the complete type variant to produce
4061 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004062 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004063 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004064 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004065 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4066 else
4067 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004068 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004069
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004070 // Emit target region as a standalone region.
4071 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4072 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004073 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataev7bb33532019-01-07 21:30:43 +00004074 auto &&SizeEmitter = [](CodeGenFunction &CGF, const OMPLoopDirective &D) {
4075 OMPLoopScope(CGF, D);
4076 // Emit calculation of the iterations count.
4077 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4078 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4079 /*IsSigned=*/false);
4080 return NumIterations;
4081 };
Alexey Bataev4920e1a2019-01-30 20:49:52 +00004082 if (IsOffloadEntry)
4083 CGM.getOpenMPRuntime().emitTargetNumIterationsCall(CGF, S, Device,
4084 SizeEmitter);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004085 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004086}
4087
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004088static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4089 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004090 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004091 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4092 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4093 CGF.EmitOMPPrivateClause(S, PrivateScope);
4094 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004095 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4096 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004097
Alexey Bataev475a7442018-01-12 19:39:11 +00004098 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004099}
4100
4101void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4102 StringRef ParentName,
4103 const OMPTargetDirective &S) {
4104 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4105 emitTargetRegion(CGF, S, Action);
4106 };
4107 llvm::Function *Fn;
4108 llvm::Constant *Addr;
4109 // Emit target region as a standalone region.
4110 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4111 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4112 assert(Fn && Addr && "Target device function emission failed.");
4113}
4114
4115void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4116 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4117 emitTargetRegion(CGF, S, Action);
4118 };
4119 emitCommonOMPTargetDirective(*this, S, CodeGen);
4120}
4121
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004122static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4123 const OMPExecutableDirective &S,
4124 OpenMPDirectiveKind InnermostKind,
4125 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004126 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004127 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004128 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4129 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004130
Alexey Bataevddf3db92018-04-13 17:31:06 +00004131 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4132 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004133 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004134 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4135 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004136
Carlo Bertollic6872252016-04-04 15:55:02 +00004137 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004138 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004139 }
4140
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004141 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004142 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4143 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004144 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004145 CapturedVars);
4146}
4147
4148void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004149 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004150 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004151 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004152 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004153 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4154 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004155 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004156 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004157 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004158 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004159 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004160 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004161 emitPostUpdateForReductionClause(*this, S,
4162 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004163}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004164
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004165static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4166 const OMPTargetTeamsDirective &S) {
4167 auto *CS = S.getCapturedStmt(OMPD_teams);
4168 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004169 // Emit teams region as a standalone region.
4170 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004171 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004172 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4173 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4174 CGF.EmitOMPPrivateClause(S, PrivateScope);
4175 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4176 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004177 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4178 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004179 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004180 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004181 };
4182 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004183 emitPostUpdateForReductionClause(CGF, S,
4184 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004185}
4186
4187void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4188 CodeGenModule &CGM, StringRef ParentName,
4189 const OMPTargetTeamsDirective &S) {
4190 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4191 emitTargetTeamsRegion(CGF, Action, S);
4192 };
4193 llvm::Function *Fn;
4194 llvm::Constant *Addr;
4195 // Emit target region as a standalone region.
4196 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4197 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4198 assert(Fn && Addr && "Target device function emission failed.");
4199}
4200
4201void CodeGenFunction::EmitOMPTargetTeamsDirective(
4202 const OMPTargetTeamsDirective &S) {
4203 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4204 emitTargetTeamsRegion(CGF, Action, S);
4205 };
4206 emitCommonOMPTargetDirective(*this, S, CodeGen);
4207}
4208
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004209static void
4210emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4211 const OMPTargetTeamsDistributeDirective &S) {
4212 Action.Enter(CGF);
4213 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4214 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4215 };
4216
4217 // Emit teams region as a standalone region.
4218 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004219 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004220 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004221 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4222 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4223 (void)PrivateScope.Privatize();
4224 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4225 CodeGenDistribute);
4226 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4227 };
4228 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4229 emitPostUpdateForReductionClause(CGF, S,
4230 [](CodeGenFunction &) { return nullptr; });
4231}
4232
4233void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4234 CodeGenModule &CGM, StringRef ParentName,
4235 const OMPTargetTeamsDistributeDirective &S) {
4236 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4237 emitTargetTeamsDistributeRegion(CGF, Action, S);
4238 };
4239 llvm::Function *Fn;
4240 llvm::Constant *Addr;
4241 // Emit target region as a standalone region.
4242 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4243 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4244 assert(Fn && Addr && "Target device function emission failed.");
4245}
4246
4247void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4248 const OMPTargetTeamsDistributeDirective &S) {
4249 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4250 emitTargetTeamsDistributeRegion(CGF, Action, S);
4251 };
4252 emitCommonOMPTargetDirective(*this, S, CodeGen);
4253}
4254
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004255static void emitTargetTeamsDistributeSimdRegion(
4256 CodeGenFunction &CGF, PrePostActionTy &Action,
4257 const OMPTargetTeamsDistributeSimdDirective &S) {
4258 Action.Enter(CGF);
4259 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4260 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4261 };
4262
4263 // Emit teams region as a standalone region.
4264 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004265 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004266 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004267 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4268 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4269 (void)PrivateScope.Privatize();
4270 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4271 CodeGenDistribute);
4272 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4273 };
4274 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4275 emitPostUpdateForReductionClause(CGF, S,
4276 [](CodeGenFunction &) { return nullptr; });
4277}
4278
4279void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4280 CodeGenModule &CGM, StringRef ParentName,
4281 const OMPTargetTeamsDistributeSimdDirective &S) {
4282 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4283 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4284 };
4285 llvm::Function *Fn;
4286 llvm::Constant *Addr;
4287 // Emit target region as a standalone region.
4288 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4289 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4290 assert(Fn && Addr && "Target device function emission failed.");
4291}
4292
4293void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4294 const OMPTargetTeamsDistributeSimdDirective &S) {
4295 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4296 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4297 };
4298 emitCommonOMPTargetDirective(*this, S, CodeGen);
4299}
4300
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004301void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4302 const OMPTeamsDistributeDirective &S) {
4303
4304 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4305 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4306 };
4307
4308 // Emit teams region as a standalone region.
4309 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004310 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004311 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004312 OMPPrivateScope PrivateScope(CGF);
4313 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4314 (void)PrivateScope.Privatize();
4315 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4316 CodeGenDistribute);
4317 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4318 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004319 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004320 emitPostUpdateForReductionClause(*this, S,
4321 [](CodeGenFunction &) { return nullptr; });
4322}
4323
Alexey Bataev999277a2017-12-06 14:31:09 +00004324void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4325 const OMPTeamsDistributeSimdDirective &S) {
4326 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4327 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4328 };
4329
4330 // Emit teams region as a standalone region.
4331 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004332 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004333 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004334 OMPPrivateScope PrivateScope(CGF);
4335 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4336 (void)PrivateScope.Privatize();
4337 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4338 CodeGenDistribute);
4339 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4340 };
4341 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4342 emitPostUpdateForReductionClause(*this, S,
4343 [](CodeGenFunction &) { return nullptr; });
4344}
4345
Carlo Bertolli62fae152017-11-20 20:46:39 +00004346void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4347 const OMPTeamsDistributeParallelForDirective &S) {
4348 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4349 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4350 S.getDistInc());
4351 };
4352
4353 // Emit teams region as a standalone region.
4354 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004355 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004356 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004357 OMPPrivateScope PrivateScope(CGF);
4358 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4359 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004360 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4361 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004362 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4363 };
4364 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4365 emitPostUpdateForReductionClause(*this, S,
4366 [](CodeGenFunction &) { return nullptr; });
4367}
4368
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004369void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4370 const OMPTeamsDistributeParallelForSimdDirective &S) {
4371 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4372 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4373 S.getDistInc());
4374 };
4375
4376 // Emit teams region as a standalone region.
4377 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004378 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004379 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004380 OMPPrivateScope PrivateScope(CGF);
4381 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4382 (void)PrivateScope.Privatize();
4383 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4384 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4385 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4386 };
4387 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4388 emitPostUpdateForReductionClause(*this, S,
4389 [](CodeGenFunction &) { return nullptr; });
4390}
4391
Carlo Bertolli52978c32018-01-03 21:12:44 +00004392static void emitTargetTeamsDistributeParallelForRegion(
4393 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4394 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004395 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004396 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4397 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4398 S.getDistInc());
4399 };
4400
4401 // Emit teams region as a standalone region.
4402 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004403 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004404 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004405 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4406 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4407 (void)PrivateScope.Privatize();
4408 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4409 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4410 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4411 };
4412
4413 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4414 CodeGenTeams);
4415 emitPostUpdateForReductionClause(CGF, S,
4416 [](CodeGenFunction &) { return nullptr; });
4417}
4418
4419void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4420 CodeGenModule &CGM, StringRef ParentName,
4421 const OMPTargetTeamsDistributeParallelForDirective &S) {
4422 // Emit SPMD target teams distribute parallel for region as a standalone
4423 // region.
4424 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4425 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4426 };
4427 llvm::Function *Fn;
4428 llvm::Constant *Addr;
4429 // Emit target region as a standalone region.
4430 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4431 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4432 assert(Fn && Addr && "Target device function emission failed.");
4433}
4434
4435void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4436 const OMPTargetTeamsDistributeParallelForDirective &S) {
4437 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4438 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4439 };
4440 emitCommonOMPTargetDirective(*this, S, CodeGen);
4441}
4442
Alexey Bataev647dd842018-01-15 20:59:40 +00004443static void emitTargetTeamsDistributeParallelForSimdRegion(
4444 CodeGenFunction &CGF,
4445 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4446 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004447 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004448 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4449 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4450 S.getDistInc());
4451 };
4452
4453 // Emit teams region as a standalone region.
4454 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004455 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004456 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004457 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4458 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4459 (void)PrivateScope.Privatize();
4460 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4461 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4462 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4463 };
4464
4465 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4466 CodeGenTeams);
4467 emitPostUpdateForReductionClause(CGF, S,
4468 [](CodeGenFunction &) { return nullptr; });
4469}
4470
4471void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4472 CodeGenModule &CGM, StringRef ParentName,
4473 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4474 // Emit SPMD target teams distribute parallel for simd region as a standalone
4475 // region.
4476 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4477 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4478 };
4479 llvm::Function *Fn;
4480 llvm::Constant *Addr;
4481 // Emit target region as a standalone region.
4482 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4483 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4484 assert(Fn && Addr && "Target device function emission failed.");
4485}
4486
4487void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4488 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4489 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4490 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4491 };
4492 emitCommonOMPTargetDirective(*this, S, CodeGen);
4493}
4494
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004495void CodeGenFunction::EmitOMPCancellationPointDirective(
4496 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004497 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004498 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004499}
4500
Alexey Bataev80909872015-07-02 11:25:17 +00004501void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004502 const Expr *IfCond = nullptr;
4503 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4504 if (C->getNameModifier() == OMPD_unknown ||
4505 C->getNameModifier() == OMPD_cancel) {
4506 IfCond = C->getCondition();
4507 break;
4508 }
4509 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004510 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004511 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004512}
4513
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004514CodeGenFunction::JumpDest
4515CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004516 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4517 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004518 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004519 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004520 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4521 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004522 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004523 Kind == OMPD_teams_distribute_parallel_for ||
4524 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004525 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004526}
Michael Wong65f367f2015-07-21 13:44:28 +00004527
Samuel Antaocc10b852016-07-28 14:23:26 +00004528void CodeGenFunction::EmitOMPUseDevicePtrClause(
4529 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4530 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4531 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4532 auto OrigVarIt = C.varlist_begin();
4533 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004534 for (const Expr *PvtVarIt : C.private_copies()) {
4535 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4536 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4537 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004538
4539 // In order to identify the right initializer we need to match the
4540 // declaration used by the mapping logic. In some cases we may get
4541 // OMPCapturedExprDecl that refers to the original declaration.
4542 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004543 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004544 // OMPCapturedExprDecl are used to privative fields of the current
4545 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004546 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004547 assert(isa<CXXThisExpr>(ME->getBase()) &&
4548 "Base should be the current struct!");
4549 MatchingVD = ME->getMemberDecl();
4550 }
4551
4552 // If we don't have information about the current list item, move on to
4553 // the next one.
4554 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4555 if (InitAddrIt == CaptureDeviceAddrMap.end())
4556 continue;
4557
Alexey Bataevddf3db92018-04-13 17:31:06 +00004558 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4559 InitAddrIt, InitVD,
4560 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004561 // Initialize the temporary initialization variable with the address we
4562 // get from the runtime library. We have to cast the source address
4563 // because it is always a void *. References are materialized in the
4564 // privatization scope, so the initialization here disregards the fact
4565 // the original variable is a reference.
4566 QualType AddrQTy =
4567 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4568 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4569 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4570 setAddrOfLocalVar(InitVD, InitAddr);
4571
4572 // Emit private declaration, it will be initialized by the value we
4573 // declaration we just added to the local declarations map.
4574 EmitDecl(*PvtVD);
4575
4576 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004577 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004578 LocalDeclMap.erase(InitVD);
4579
4580 // Return the address of the private variable.
4581 return GetAddrOfLocalVar(PvtVD);
4582 });
4583 assert(IsRegistered && "firstprivate var already registered as private");
4584 // Silence the warning about unused variable.
4585 (void)IsRegistered;
4586
4587 ++OrigVarIt;
4588 ++InitIt;
4589 }
4590}
4591
Michael Wong65f367f2015-07-21 13:44:28 +00004592// Generate the instructions for '#pragma omp target data' directive.
4593void CodeGenFunction::EmitOMPTargetDataDirective(
4594 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004595 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4596
4597 // Create a pre/post action to signal the privatization of the device pointer.
4598 // This action can be replaced by the OpenMP runtime code generation to
4599 // deactivate privatization.
4600 bool PrivatizeDevicePointers = false;
4601 class DevicePointerPrivActionTy : public PrePostActionTy {
4602 bool &PrivatizeDevicePointers;
4603
4604 public:
4605 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4606 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4607 void Enter(CodeGenFunction &CGF) override {
4608 PrivatizeDevicePointers = true;
4609 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004610 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004611 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4612
4613 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004614 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004615 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004616 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004617 };
4618
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004619 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004620 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4621 &InnermostCodeGen](CodeGenFunction &CGF,
4622 PrePostActionTy &Action) {
4623 RegionCodeGenTy RCG(InnermostCodeGen);
4624 PrivatizeDevicePointers = false;
4625
4626 // Call the pre-action to change the status of PrivatizeDevicePointers if
4627 // needed.
4628 Action.Enter(CGF);
4629
4630 if (PrivatizeDevicePointers) {
4631 OMPPrivateScope PrivateScope(CGF);
4632 // Emit all instances of the use_device_ptr clause.
4633 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4634 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4635 Info.CaptureDeviceAddrMap);
4636 (void)PrivateScope.Privatize();
4637 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004638 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004639 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004640 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004641 };
4642
4643 // Forward the provided action to the privatization codegen.
4644 RegionCodeGenTy PrivRCG(PrivCodeGen);
4645 PrivRCG.setAction(Action);
4646
4647 // Notwithstanding the body of the region is emitted as inlined directive,
4648 // we don't use an inline scope as changes in the references inside the
4649 // region are expected to be visible outside, so we do not privative them.
4650 OMPLexicalScope Scope(CGF, S);
4651 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4652 PrivRCG);
4653 };
4654
4655 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004656
4657 // If we don't have target devices, don't bother emitting the data mapping
4658 // code.
4659 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004660 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004661 return;
4662 }
4663
4664 // Check if we have any if clause associated with the directive.
4665 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004666 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004667 IfCond = C->getCondition();
4668
4669 // Check if we have any device clause associated with the directive.
4670 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004671 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004672 Device = C->getDevice();
4673
Samuel Antaocc10b852016-07-28 14:23:26 +00004674 // Set the action to signal privatization of device pointers.
4675 RCG.setAction(PrivAction);
4676
4677 // Emit region code.
4678 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4679 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004680}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004681
Samuel Antaodf67fc42016-01-19 19:15:56 +00004682void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4683 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004684 // If we don't have target devices, don't bother emitting the data mapping
4685 // code.
4686 if (CGM.getLangOpts().OMPTargetTriples.empty())
4687 return;
4688
4689 // Check if we have any if clause associated with the directive.
4690 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004691 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004692 IfCond = C->getCondition();
4693
4694 // Check if we have any device clause associated with the directive.
4695 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004696 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004697 Device = C->getDevice();
4698
Alexey Bataev475a7442018-01-12 19:39:11 +00004699 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004700 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004701}
4702
Samuel Antao72590762016-01-19 20:04:50 +00004703void CodeGenFunction::EmitOMPTargetExitDataDirective(
4704 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004705 // If we don't have target devices, don't bother emitting the data mapping
4706 // code.
4707 if (CGM.getLangOpts().OMPTargetTriples.empty())
4708 return;
4709
4710 // Check if we have any if clause associated with the directive.
4711 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004712 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004713 IfCond = C->getCondition();
4714
4715 // Check if we have any device clause associated with the directive.
4716 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004717 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004718 Device = C->getDevice();
4719
Alexey Bataev475a7442018-01-12 19:39:11 +00004720 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004721 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004722}
4723
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004724static void emitTargetParallelRegion(CodeGenFunction &CGF,
4725 const OMPTargetParallelDirective &S,
4726 PrePostActionTy &Action) {
4727 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004728 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004729 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004730 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004731 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004732 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4733 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4734 CGF.EmitOMPPrivateClause(S, PrivateScope);
4735 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4736 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004737 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4738 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004739 // TODO: Add support for clauses.
4740 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004741 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004742 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004743 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4744 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004745 emitPostUpdateForReductionClause(CGF, S,
4746 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004747}
4748
4749void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4750 CodeGenModule &CGM, StringRef ParentName,
4751 const OMPTargetParallelDirective &S) {
4752 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4753 emitTargetParallelRegion(CGF, S, Action);
4754 };
4755 llvm::Function *Fn;
4756 llvm::Constant *Addr;
4757 // Emit target region as a standalone region.
4758 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4759 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4760 assert(Fn && Addr && "Target device function emission failed.");
4761}
4762
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004763void CodeGenFunction::EmitOMPTargetParallelDirective(
4764 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004765 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4766 emitTargetParallelRegion(CGF, S, Action);
4767 };
4768 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004769}
4770
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004771static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4772 const OMPTargetParallelForDirective &S,
4773 PrePostActionTy &Action) {
4774 Action.Enter(CGF);
4775 // Emit directive as a combined directive that consists of two implicit
4776 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004777 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4778 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004779 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4780 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004781 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4782 emitDispatchForLoopBounds);
4783 };
4784 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4785 emitEmptyBoundParameters);
4786}
4787
4788void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4789 CodeGenModule &CGM, StringRef ParentName,
4790 const OMPTargetParallelForDirective &S) {
4791 // Emit SPMD target parallel for region as a standalone region.
4792 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4793 emitTargetParallelForRegion(CGF, S, Action);
4794 };
4795 llvm::Function *Fn;
4796 llvm::Constant *Addr;
4797 // Emit target region as a standalone region.
4798 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4799 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4800 assert(Fn && Addr && "Target device function emission failed.");
4801}
4802
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004803void CodeGenFunction::EmitOMPTargetParallelForDirective(
4804 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004805 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4806 emitTargetParallelForRegion(CGF, S, Action);
4807 };
4808 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004809}
4810
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004811static void
4812emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4813 const OMPTargetParallelForSimdDirective &S,
4814 PrePostActionTy &Action) {
4815 Action.Enter(CGF);
4816 // Emit directive as a combined directive that consists of two implicit
4817 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004818 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4819 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004820 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4821 emitDispatchForLoopBounds);
4822 };
4823 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4824 emitEmptyBoundParameters);
4825}
4826
4827void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4828 CodeGenModule &CGM, StringRef ParentName,
4829 const OMPTargetParallelForSimdDirective &S) {
4830 // Emit SPMD target parallel for region as a standalone region.
4831 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4832 emitTargetParallelForSimdRegion(CGF, S, Action);
4833 };
4834 llvm::Function *Fn;
4835 llvm::Constant *Addr;
4836 // Emit target region as a standalone region.
4837 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4838 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4839 assert(Fn && Addr && "Target device function emission failed.");
4840}
4841
4842void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4843 const OMPTargetParallelForSimdDirective &S) {
4844 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4845 emitTargetParallelForSimdRegion(CGF, S, Action);
4846 };
4847 emitCommonOMPTargetDirective(*this, S, CodeGen);
4848}
4849
Alexey Bataev7292c292016-04-25 12:22:29 +00004850/// Emit a helper variable and return corresponding lvalue.
4851static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4852 const ImplicitParamDecl *PVD,
4853 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004854 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
4855 Privates.addPrivate(VDecl,
4856 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00004857}
4858
4859void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4860 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4861 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004862 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004863 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4864 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004865 const Expr *IfCond = nullptr;
4866 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4867 if (C->getNameModifier() == OMPD_unknown ||
4868 C->getNameModifier() == OMPD_taskloop) {
4869 IfCond = C->getCondition();
4870 break;
4871 }
4872 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004873
4874 OMPTaskDataTy Data;
4875 // Check if taskloop must be emitted without taskgroup.
4876 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004877 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004878 Data.Tied = true;
4879 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004880 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4881 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004882 Data.Schedule.setInt(/*IntVal=*/false);
4883 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004884 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4885 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004886 Data.Schedule.setInt(/*IntVal=*/true);
4887 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004888 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004889
4890 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4891 // if (PreCond) {
4892 // for (IV in 0..LastIteration) BODY;
4893 // <Final counter/linear vars updates>;
4894 // }
4895 //
4896
4897 // Emit: if (PreCond) - begin.
4898 // If the condition constant folds and can be elided, avoid emitting the
4899 // whole loop.
4900 bool CondConstant;
4901 llvm::BasicBlock *ContBlock = nullptr;
4902 OMPLoopScope PreInitScope(CGF, S);
4903 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4904 if (!CondConstant)
4905 return;
4906 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004907 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00004908 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4909 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4910 CGF.getProfileCount(&S));
4911 CGF.EmitBlock(ThenBlock);
4912 CGF.incrementProfileCounter(&S);
4913 }
4914
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004915 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4916 CGF.EmitOMPSimdInit(S);
4917
Alexey Bataev7292c292016-04-25 12:22:29 +00004918 OMPPrivateScope LoopScope(CGF);
4919 // Emit helper vars inits.
4920 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4921 auto *I = CS->getCapturedDecl()->param_begin();
4922 auto *LBP = std::next(I, LowerBound);
4923 auto *UBP = std::next(I, UpperBound);
4924 auto *STP = std::next(I, Stride);
4925 auto *LIP = std::next(I, LastIter);
4926 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4927 LoopScope);
4928 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4929 LoopScope);
4930 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4931 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4932 LoopScope);
4933 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004934 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004935 (void)LoopScope.Privatize();
4936 // Emit the loop iteration variable.
4937 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004938 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004939 CGF.EmitVarDecl(*IVDecl);
4940 CGF.EmitIgnoredExpr(S.getInit());
4941
4942 // Emit the iterations count variable.
4943 // If it is not a variable, Sema decided to calculate iterations count on
4944 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00004945 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004946 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4947 // Emit calculation of the iterations count.
4948 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4949 }
4950
4951 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4952 S.getInc(),
4953 [&S](CodeGenFunction &CGF) {
4954 CGF.EmitOMPLoopBody(S, JumpDest());
4955 CGF.EmitStopPoint(&S);
4956 },
4957 [](CodeGenFunction &) {});
4958 // Emit: if (PreCond) - end.
4959 if (ContBlock) {
4960 CGF.EmitBranch(ContBlock);
4961 CGF.EmitBlock(ContBlock, true);
4962 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004963 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4964 if (HasLastprivateClause) {
4965 CGF.EmitOMPLastprivateClauseFinal(
4966 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4967 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4968 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004969 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004970 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004971 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004972 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00004973 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004974 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004975 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
4976 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004977 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004978 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004979 OutlinedFn, SharedsTy,
4980 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004981 };
4982 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4983 CodeGen);
4984 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004985 if (Data.Nogroup) {
4986 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4987 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004988 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4989 *this,
4990 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4991 PrePostActionTy &Action) {
4992 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004993 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4994 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004995 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004996 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00004997 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004998}
4999
Alexey Bataev49f6e782015-12-01 04:18:41 +00005000void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005001 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005002}
5003
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005004void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5005 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005006 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005007}
Samuel Antao686c70c2016-05-26 17:30:50 +00005008
5009// Generate the instructions for '#pragma omp target update' directive.
5010void CodeGenFunction::EmitOMPTargetUpdateDirective(
5011 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005012 // If we don't have target devices, don't bother emitting the data mapping
5013 // code.
5014 if (CGM.getLangOpts().OMPTargetTriples.empty())
5015 return;
5016
5017 // Check if we have any if clause associated with the directive.
5018 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005019 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005020 IfCond = C->getCondition();
5021
5022 // Check if we have any device clause associated with the directive.
5023 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005024 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005025 Device = C->getDevice();
5026
Alexey Bataev475a7442018-01-12 19:39:11 +00005027 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005028 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005029}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005030
5031void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5032 const OMPExecutableDirective &D) {
5033 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5034 return;
5035 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5036 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5037 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5038 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005039 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005040 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005041 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005042 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5043 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5044 LValue GlobLVal = CGF.EmitLValue(E);
5045 LoopGlobals.addPrivate(
5046 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
5047 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005048 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005049 // Emit only those that were not explicitly referenced in clauses.
5050 if (!CGF.LocalDeclMap.count(VD))
5051 CGF.EmitVarDecl(*VD);
5052 }
5053 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005054 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5055 if (!C->getNumForLoops())
5056 continue;
5057 for (unsigned I = LD->getCollapsedNumber(),
5058 E = C->getLoopNumIterations().size();
5059 I < E; ++I) {
5060 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005061 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005062 // Emit only those that were not explicitly referenced in clauses.
5063 if (!CGF.LocalDeclMap.count(VD))
5064 CGF.EmitVarDecl(*VD);
5065 }
5066 }
5067 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005068 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005069 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005070 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005071 }
5072 };
5073 OMPSimdLexicalScope Scope(*this, D);
5074 CGM.getOpenMPRuntime().emitInlinedDirective(
5075 *this,
5076 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5077 : D.getDirectiveKind(),
5078 CodeGen);
5079}