blob: 2884eb58017fbafbb198dd1c335bb225d074834b [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 Bataeva839ddd2016-03-17 10:19:46 +000021#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000028class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000029 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000031 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
32 if (const auto *PreInit =
33 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000035 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000036 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000037 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000038 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000069 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000070 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000075 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000076 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000078 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000079 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80 return CGF.EmitLValue(&DRE).getAddress();
81 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000123 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000124 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000126 (void)PreCondVars.setVarAddr(
127 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000128 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000129 (void)PreCondVars.apply(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000130 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000131 for (const auto *I : PreInits->decls())
132 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000133 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000134 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000135 }
136
137public:
138 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
139 : CodeGenFunction::RunCleanupsScope(CGF) {
140 emitPreInitStmt(CGF, S);
141 }
142};
143
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000144class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
145 CodeGenFunction::OMPPrivateScope InlinedShareds;
146
147 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
148 return CGF.LambdaCaptureFields.lookup(VD) ||
149 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
150 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
151 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
152 }
153
154public:
155 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
156 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
157 InlinedShareds(CGF) {
158 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000159 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
160 if (const auto *PreInit =
161 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000162 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000163 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000164 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000165 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000166 CodeGenFunction::AutoVarEmission Emission =
167 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
168 CGF.EmitAutoVarCleanups(Emission);
169 }
170 }
171 }
172 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
173 for (const Expr *E : UDP->varlists()) {
174 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
175 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
176 CGF.EmitVarDecl(*OED);
177 }
178 }
179 }
180 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
181 CGF.EmitOMPPrivateClause(S, InlinedShareds);
182 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
183 if (const Expr *E = TG->getReductionRef())
184 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
185 }
186 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
187 while (CS) {
188 for (auto &C : CS->captures()) {
189 if (C.capturesVariable() || C.capturesVariableByCopy()) {
190 auto *VD = C.getCapturedVar();
191 assert(VD == VD->getCanonicalDecl() &&
192 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000193 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000194 isCapturedVar(CGF, VD) ||
195 (CGF.CapturedStmtInfo &&
196 InlinedShareds.isGlobalVarCaptured(VD)),
197 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000198 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000199 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
200 return CGF.EmitLValue(&DRE).getAddress();
201 });
202 }
203 }
204 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
205 }
206 (void)InlinedShareds.Privatize();
207 }
208};
209
Alexey Bataev3392d762016-02-16 11:18:12 +0000210} // namespace
211
Alexey Bataevf8365372017-11-17 17:57:25 +0000212static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
213 const OMPExecutableDirective &S,
214 const RegionCodeGenTy &CodeGen);
215
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000216LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000217 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
218 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000219 OrigVD = OrigVD->getCanonicalDecl();
220 bool IsCaptured =
221 LambdaCaptureFields.lookup(OrigVD) ||
222 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
223 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000224 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000225 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
226 return EmitLValue(&DRE);
227 }
228 }
229 return EmitLValue(E);
230}
231
Alexey Bataev1189bd02016-01-26 12:20:39 +0000232llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000233 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000234 llvm::Value *Size = nullptr;
235 auto SizeInChars = C.getTypeSizeInChars(Ty);
236 if (SizeInChars.isZero()) {
237 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000238 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
239 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000240 Ty = VlaSize.Type;
241 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
242 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000243 }
244 SizeInChars = C.getTypeSizeInChars(Ty);
245 if (SizeInChars.isZero())
246 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000247 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
248 }
249 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000250}
251
Alexey Bataev2377fe92015-09-10 08:12:02 +0000252void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000253 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000254 const RecordDecl *RD = S.getCapturedRecordDecl();
255 auto CurField = RD->field_begin();
256 auto CurCap = S.captures().begin();
257 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
258 E = S.capture_init_end();
259 I != E; ++I, ++CurField, ++CurCap) {
260 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000261 const VariableArrayType *VAT = CurField->getCapturedVLAType();
262 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000263 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000264 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000265 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000266 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000267 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000268
269 // If the field is not a pointer, we need to save the actual value
270 // and load it as a void pointer.
271 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000272 ASTContext &Ctx = getContext();
273 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000274 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000275 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000276 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
277
Alexey Bataevddf3db92018-04-13 17:31:06 +0000278 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000279 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000280 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000281 LValue SrcLV =
282 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
283
284 // Store the value using the source type pointer.
285 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
286
287 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000288 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000289 }
290 CapturedVars.push_back(CV);
291 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000292 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000293 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 }
296}
297
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000298static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
299 QualType DstType, StringRef Name,
300 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000301 bool isReferenceType = false) {
302 ASTContext &Ctx = CGF.getContext();
303
Alexey Bataevddf3db92018-04-13 17:31:06 +0000304 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
305 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
306 Ctx.getPointerType(DstType), Loc);
307 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000308 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
309 .getAddress();
310
311 // If we are dealing with references we need to return the address of the
312 // reference instead of the reference of the value.
313 if (isReferenceType) {
314 QualType RefType = Ctx.getLValueReferenceType(DstType);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000315 llvm::Value *RefVal = TmpAddr.getPointer();
316 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name, ".ref"));
317 LValue TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
318 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000319 }
320
321 return TmpAddr;
322}
323
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000324static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000325 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000326 return C.getLValueReferenceType(
327 getCanonicalParamType(C, T.getNonReferenceType()),
328 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000329 if (T->isPointerType())
330 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000331 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
332 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000333 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000334 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000335 return C.getCanonicalType(T);
336 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000337 return C.getCanonicalParamType(T);
338}
339
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000340namespace {
341 /// Contains required data for proper outlined function codegen.
342 struct FunctionOptions {
343 /// Captured statement for which the function is generated.
344 const CapturedStmt *S = nullptr;
345 /// true if cast to/from UIntPtr is required for variables captured by
346 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000347 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000348 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000349 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000350 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000351 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000352 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000353 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
354 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000355 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000356 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
357 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000358 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000359 };
360}
361
Alexey Bataeve754b182017-08-09 19:38:53 +0000362static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000363 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000364 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000365 &LocalAddrs,
366 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
367 &VLASizes,
368 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
369 const CapturedDecl *CD = FO.S->getCapturedDecl();
370 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371 assert(CD->hasBody() && "missing CapturedDecl body");
372
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000373 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000375 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000377 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000378 Args.append(CD->param_begin(),
379 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000380 TargetArgs.append(
381 CD->param_begin(),
382 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000383 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000384 FunctionDecl *DebugFunctionDecl = nullptr;
385 if (!FO.UIntPtrCastRequired) {
386 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000387 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000388 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000389 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000390 SourceLocation(), DeclarationName(), FunctionTy,
391 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
392 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000393 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000394 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 QualType ArgType = FD->getType();
396 IdentifierInfo *II = nullptr;
397 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000398
399 // If this is a capture by copy and the type is not a pointer, the outlined
400 // function argument type should be uintptr and the value properly casted to
401 // uintptr. This is necessary given that the runtime library is only able to
402 // deal with pointers. We can pass in the same way the VLA type sizes to the
403 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000404 if (FO.UIntPtrCastRequired &&
405 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
406 I->capturesVariableArrayType()))
407 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000408
409 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000410 CapVar = I->getCapturedVar();
411 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000412 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000413 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000414 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000415 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000416 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000417 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000418 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000419 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000420 VarDecl *Arg;
421 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
422 Arg = ParmVarDecl::Create(
423 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000424 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000425 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
426 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
427 } else {
428 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
429 II, ArgType, ImplicitParamDecl::Other);
430 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000431 Args.emplace_back(Arg);
432 // Do not cast arguments if we emit function with non-original types.
433 TargetArgs.emplace_back(
434 FO.UIntPtrCastRequired
435 ? Arg
436 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000437 ++I;
438 }
439 Args.append(
440 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
441 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000442 TargetArgs.append(
443 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
444 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000445
446 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000447 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000448 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
450
Alexey Bataevddf3db92018-04-13 17:31:06 +0000451 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000452 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
453 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000454 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
455 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000456 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000457 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458
459 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000460 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000461 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000462 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000463 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000464 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000465 // Do not map arguments if we emit function with non-original types.
466 Address LocalAddr(Address::invalid());
467 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
468 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
469 TargetArgs[Cnt]);
470 } else {
471 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
472 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000473 // If we are capturing a pointer by copy we don't need to do anything, just
474 // use the value that we get from the arguments.
475 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000476 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000477 // If the variable is a reference we need to materialize it here.
478 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000479 Address RefAddr = CGF.CreateMemTemp(
480 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
481 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
482 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000483 LocalAddr = RefAddr;
484 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000485 if (!FO.RegisterCastedArgsOnly)
486 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000487 ++Cnt;
488 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000489 continue;
490 }
491
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000492 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
493 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000494 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000495 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000496 ArgLVal = CGF.MakeAddrLValue(
497 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
498 Args[Cnt]->getName(), ArgLVal),
499 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000500 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000501 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
502 const VariableArrayType *VAT = FD->getCapturedVLAType();
503 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000504 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000505 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000506 QualType VarTy = Var->getType();
507 Address ArgAddr = ArgLVal.getAddress();
508 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000509 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000510 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000511 } else if (!VarTy->isVariablyModifiedType() ||
512 !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000513 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000514 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
516 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000518 if (!FO.RegisterCastedArgsOnly) {
519 LocalAddrs.insert(
520 {Args[Cnt],
521 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
522 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000523 } else if (I->capturesVariableByCopy()) {
524 assert(!FD->getType()->isAnyPointerType() &&
525 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000526 const VarDecl *Var = I->getCapturedVar();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000527 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000528 LocalAddrs.insert(
529 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000530 {Var, FO.UIntPtrCastRequired
531 ? castValueFromUintptr(CGF, I->getLocation(),
532 FD->getType(), Args[Cnt]->getName(),
533 ArgLVal, VarTy->isReferenceType())
534 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000535 } else {
536 // If 'this' is captured, load it into CXXThisValue.
537 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000538 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000539 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000540 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000541 ++Cnt;
542 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 }
544
Alexey Bataeve754b182017-08-09 19:38:53 +0000545 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000546}
547
548llvm::Function *
549CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
550 assert(
551 CapturedStmtInfo &&
552 "CapturedStmtInfo should be set when generating the captured function");
553 const CapturedDecl *CD = S.getCapturedDecl();
554 // Build the argument list.
555 bool NeedWrapperFunction =
556 getDebugInfo() &&
557 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
558 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000559 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000560 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000561 SmallString<256> Buffer;
562 llvm::raw_svector_ostream Out(Buffer);
563 Out << CapturedStmtInfo->getHelperName();
564 if (NeedWrapperFunction)
565 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000566 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000567 Out.str());
568 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
569 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000570 for (const auto &LocalAddrPair : LocalAddrs) {
571 if (LocalAddrPair.second.first) {
572 setAddrOfLocalVar(LocalAddrPair.second.first,
573 LocalAddrPair.second.second);
574 }
575 }
576 for (const auto &VLASizePair : VLASizes)
577 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000578 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000579 CapturedStmtInfo->EmitBody(*this, CD->getBody());
580 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000581 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000582 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000583
Alexey Bataevefd884d2017-08-04 21:26:25 +0000584 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000585 /*RegisterCastedArgsOnly=*/true,
586 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000587 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000588 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 Args.clear();
590 LocalAddrs.clear();
591 VLASizes.clear();
592 llvm::Function *WrapperF =
593 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000594 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000595 llvm::SmallVector<llvm::Value *, 4> CallArgs;
596 for (const auto *Arg : Args) {
597 llvm::Value *CallArg;
598 auto I = LocalAddrs.find(Arg);
599 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000600 LValue LV = WrapperCGF.MakeAddrLValue(
601 I->second.second,
602 I->second.first ? I->second.first->getType() : Arg->getType(),
603 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000604 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000605 } else {
606 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000607 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000608 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000609 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000610 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000611 Arg->getType(),
612 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000613 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000614 }
615 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000616 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000618 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 WrapperCGF.FinishFunction();
621 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000622}
623
Alexey Bataev9959db52014-05-06 10:08:46 +0000624//===----------------------------------------------------------------------===//
625// OpenMP Directive Emission
626//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000627void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000629 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630 // Perform element-by-element initialization.
631 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000632
633 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000634 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
635 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000636 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
637
Alexey Bataevddf3db92018-04-13 17:31:06 +0000638 llvm::Value *SrcBegin = SrcAddr.getPointer();
639 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000641 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000643 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
644 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
645 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000646 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
647 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000648
Alexey Bataev420d45b2015-04-14 05:11:24 +0000649 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000650 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000651 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000652
653 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
654
655 llvm::PHINode *SrcElementPHI =
656 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
657 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
658 Address SrcElementCurrent =
659 Address(SrcElementPHI,
660 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
661
662 llvm::PHINode *DestElementPHI =
663 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
664 DestElementPHI->addIncoming(DestBegin, EntryBB);
665 Address DestElementCurrent =
666 Address(DestElementPHI,
667 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000668
Alexey Bataev420d45b2015-04-14 05:11:24 +0000669 // Emit copy.
670 CopyGen(DestElementCurrent, SrcElementCurrent);
671
672 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000673 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000674 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000675 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000676 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000677 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000678 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000679 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
680 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000681 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
682 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000683
684 // Done.
685 EmitBlock(DoneBB, /*IsFinished=*/true);
686}
687
John McCall7f416cc2015-09-08 08:05:57 +0000688void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
689 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000690 const VarDecl *SrcVD, const Expr *Copy) {
691 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000692 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000693 if (BO && BO->getOpcode() == BO_Assign) {
694 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000695 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
696 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
697 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000698 } else {
699 // For arrays with complex element types perform element by element
700 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000701 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000703 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000704 // Working with the single array element, so have to remap
705 // destination and source variables to corresponding array
706 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000707 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000708 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
709 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000711 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000712 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000713 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 } else {
715 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000716 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000717 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
718 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000719 (void)Remap.Privatize();
720 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000721 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000722 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000723}
724
Alexey Bataev69c62a92015-04-15 04:52:20 +0000725bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
726 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000727 if (!HaveInsertPoint())
728 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000729 bool FirstprivateIsLastprivate = false;
730 llvm::DenseSet<const VarDecl *> Lastprivates;
731 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
732 for (const auto *D : C->varlists())
733 Lastprivates.insert(
734 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
735 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000736 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000737 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
738 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
739 // Force emission of the firstprivate copy if the directive does not emit
740 // outlined function, like omp for, omp simd, omp distribute etc.
741 bool MustEmitFirstprivateCopy =
742 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000743 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000744 auto IRef = C->varlist_begin();
745 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000746 for (const Expr *IInit : C->private_copies()) {
747 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000748 bool ThisFirstprivateIsLastprivate =
749 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000750 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000751 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752 !FD->getType()->isReferenceType()) {
753 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
754 ++IRef;
755 ++InitsRef;
756 continue;
757 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000758 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000759 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000760 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000761 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
762 const auto *VDInit =
763 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000764 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000765 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000766 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
767 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000768 LValue OriginalLVal = EmitLValue(&DRE);
Alexey Bataevfeddd642016-04-22 09:05:03 +0000769 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000770 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000771 // Emit VarDecl with copy init for arrays.
772 // Get the address of the original variable captured in current
773 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000774 IsRegistered = PrivateScope.addPrivate(
775 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
776 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
777 const Expr *Init = VD->getInit();
778 if (!isa<CXXConstructExpr>(Init) ||
779 isTrivialInitializer(Init)) {
780 // Perform simple memcpy.
781 LValue Dest =
782 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
783 EmitAggregateAssign(Dest, OriginalLVal, Type);
784 } else {
785 EmitOMPAggregateAssign(
786 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
787 Type,
788 [this, VDInit, Init](Address DestElement,
789 Address SrcElement) {
790 // Clean up any temporaries needed by the
791 // initialization.
792 RunCleanupsScope InitScope(*this);
793 // Emit initialization for single element.
794 setAddrOfLocalVar(VDInit, SrcElement);
795 EmitAnyExprToMem(Init, DestElement,
796 Init->getType().getQualifiers(),
797 /*IsInitializer*/ false);
798 LocalDeclMap.erase(VDInit);
799 });
800 }
801 EmitAutoVarCleanups(Emission);
802 return Emission.getAllocatedAddress();
803 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000804 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000805 Address OriginalAddr = OriginalLVal.getAddress();
806 IsRegistered = PrivateScope.addPrivate(
807 OrigVD, [this, VDInit, OriginalAddr, VD]() {
808 // Emit private VarDecl with copy init.
809 // Remap temp VDInit variable to the address of the original
810 // variable (for proper handling of captured global variables).
811 setAddrOfLocalVar(VDInit, OriginalAddr);
812 EmitDecl(*VD);
813 LocalDeclMap.erase(VDInit);
814 return GetAddrOfLocalVar(VD);
815 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000816 }
817 assert(IsRegistered &&
818 "firstprivate var already registered as private");
819 // Silence the warning about unused variable.
820 (void)IsRegistered;
821 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000822 ++IRef;
823 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000824 }
825 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000826 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000827}
828
Alexey Bataev03b340a2014-10-21 03:16:40 +0000829void CodeGenFunction::EmitOMPPrivateClause(
830 const OMPExecutableDirective &D,
831 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000832 if (!HaveInsertPoint())
833 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000834 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000835 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000836 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000837 for (const Expr *IInit : C->private_copies()) {
838 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000839 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000840 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
841 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
842 // Emit private VarDecl with copy init.
843 EmitDecl(*VD);
844 return GetAddrOfLocalVar(VD);
845 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000846 assert(IsRegistered && "private var already registered as private");
847 // Silence the warning about unused variable.
848 (void)IsRegistered;
849 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000850 ++IRef;
851 }
852 }
853}
854
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000856 if (!HaveInsertPoint())
857 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000858 // threadprivate_var1 = master_threadprivate_var1;
859 // operator=(threadprivate_var2, master_threadprivate_var2);
860 // ...
861 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000862 llvm::DenseSet<const VarDecl *> CopiedVars;
863 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000864 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000865 auto IRef = C->varlist_begin();
866 auto ISrcRef = C->source_exprs().begin();
867 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000868 for (const Expr *AssignOp : C->assignment_ops()) {
869 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000870 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000871 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000872 // Get the address of the master variable. If we are emitting code with
873 // TLS support, the address is passed from the master as field in the
874 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000875 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000876 if (getLangOpts().OpenMPUseTLS &&
877 getContext().getTargetInfo().isTLSSupported()) {
878 assert(CapturedStmtInfo->lookup(VD) &&
879 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000880 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
881 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000882 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000883 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000884 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000885 MasterAddr =
886 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
887 : CGM.GetAddrOfGlobal(VD),
888 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000889 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000890 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000891 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000892 if (CopiedVars.size() == 1) {
893 // At first check if current thread is a master thread. If it is, no
894 // need to copy data.
895 CopyBegin = createBasicBlock("copyin.not.master");
896 CopyEnd = createBasicBlock("copyin.not.master.end");
897 Builder.CreateCondBr(
898 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000899 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000900 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
901 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000902 CopyBegin, CopyEnd);
903 EmitBlock(CopyBegin);
904 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000905 const auto *SrcVD =
906 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
907 const auto *DestVD =
908 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000909 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000910 }
911 ++IRef;
912 ++ISrcRef;
913 ++IDestRef;
914 }
915 }
916 if (CopyEnd) {
917 // Exit out of copying procedure for non-master thread.
918 EmitBlock(CopyEnd, /*IsFinished=*/true);
919 return true;
920 }
921 return false;
922}
923
Alexey Bataev38e89532015-04-16 04:54:05 +0000924bool CodeGenFunction::EmitOMPLastprivateClauseInit(
925 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000926 if (!HaveInsertPoint())
927 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000928 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000929 llvm::DenseSet<const VarDecl *> SIMDLCVs;
930 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000931 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
932 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000933 SIMDLCVs.insert(
934 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
935 }
936 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000938 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000939 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000940 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
941 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000942 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000943 auto IRef = C->varlist_begin();
944 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000945 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000946 // Keep the address of the original variable for future update at the end
947 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000948 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000949 // Taskloops do not require additional initialization, it is done in
950 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000951 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000952 const auto *DestVD =
953 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
954 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000955 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
956 /*RefersToEnclosingVariableOrCapture=*/
957 CapturedStmtInfo->lookup(OrigVD) != nullptr,
958 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +0000959 return EmitLValue(&DRE).getAddress();
960 });
961 // Check if the variable is also a firstprivate: in this case IInit is
962 // not generated. Initialization of this variable will happen in codegen
963 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000964 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000965 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
966 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +0000967 // Emit private VarDecl with copy init.
968 EmitDecl(*VD);
969 return GetAddrOfLocalVar(VD);
970 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000971 assert(IsRegistered &&
972 "lastprivate var already registered as private");
973 (void)IsRegistered;
974 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000975 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000976 ++IRef;
977 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000978 }
979 }
980 return HasAtLeastOneLastprivate;
981}
982
983void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000984 const OMPExecutableDirective &D, bool NoFinals,
985 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000986 if (!HaveInsertPoint())
987 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000988 // Emit following code:
989 // if (<IsLastIterCond>) {
990 // orig_var1 = private_orig_var1;
991 // ...
992 // orig_varn = private_orig_varn;
993 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000994 llvm::BasicBlock *ThenBB = nullptr;
995 llvm::BasicBlock *DoneBB = nullptr;
996 if (IsLastIterCond) {
997 ThenBB = createBasicBlock(".omp.lastprivate.then");
998 DoneBB = createBasicBlock(".omp.lastprivate.done");
999 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1000 EmitBlock(ThenBB);
1001 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001002 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1003 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001004 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001005 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001006 for (const Expr *F : LoopDirective->finals()) {
1007 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001008 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1009 if (NoFinals)
1010 AlreadyEmittedVars.insert(D);
1011 else
1012 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001013 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001014 }
1015 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001016 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1017 auto IRef = C->varlist_begin();
1018 auto ISrcRef = C->source_exprs().begin();
1019 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001020 for (const Expr *AssignOp : C->assignment_ops()) {
1021 const auto *PrivateVD =
1022 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001023 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001024 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001025 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1026 // If lastprivate variable is a loop control variable for loop-based
1027 // directive, update its value before copyin back to original
1028 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001029 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001030 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001031 const auto *SrcVD =
1032 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1033 const auto *DestVD =
1034 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001035 // Get the address of the original variable.
1036 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1037 // Get the address of the private variable.
1038 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001039 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001040 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001041 Address(Builder.CreateLoad(PrivateAddr),
1042 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001043 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001044 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001045 ++IRef;
1046 ++ISrcRef;
1047 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001048 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001049 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001050 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001051 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001052 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001053 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001054}
1055
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001056void CodeGenFunction::EmitOMPReductionClauseInit(
1057 const OMPExecutableDirective &D,
1058 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001059 if (!HaveInsertPoint())
1060 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 SmallVector<const Expr *, 4> Shareds;
1062 SmallVector<const Expr *, 4> Privates;
1063 SmallVector<const Expr *, 4> ReductionOps;
1064 SmallVector<const Expr *, 4> LHSs;
1065 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001066 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001067 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001068 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001069 auto ILHS = C->lhs_exprs().begin();
1070 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001071 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001072 Shareds.emplace_back(Ref);
1073 Privates.emplace_back(*IPriv);
1074 ReductionOps.emplace_back(*IRed);
1075 LHSs.emplace_back(*ILHS);
1076 RHSs.emplace_back(*IRHS);
1077 std::advance(IPriv, 1);
1078 std::advance(IRed, 1);
1079 std::advance(ILHS, 1);
1080 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001081 }
1082 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001083 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1084 unsigned Count = 0;
1085 auto ILHS = LHSs.begin();
1086 auto IRHS = RHSs.begin();
1087 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001088 for (const Expr *IRef : Shareds) {
1089 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001090 // Emit private VarDecl with reduction init.
1091 RedCG.emitSharedLValue(*this, Count);
1092 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001093 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001094 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1095 RedCG.getSharedLValue(Count),
1096 [&Emission](CodeGenFunction &CGF) {
1097 CGF.EmitAutoVarInit(Emission);
1098 return true;
1099 });
1100 EmitAutoVarCleanups(Emission);
1101 Address BaseAddr = RedCG.adjustPrivateAddress(
1102 *this, Count, Emission.getAllocatedAddress());
1103 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001104 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001105 assert(IsRegistered && "private var already registered as private");
1106 // Silence the warning about unused variable.
1107 (void)IsRegistered;
1108
Alexey Bataevddf3db92018-04-13 17:31:06 +00001109 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1110 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001111 QualType Type = PrivateVD->getType();
1112 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1113 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 // Store the address of the original variable associated with the LHS
1115 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001116 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 return RedCG.getSharedLValue(Count).getAddress();
1118 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001119 PrivateScope.addPrivate(
1120 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001121 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1122 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001123 // Store the address of the original variable associated with the LHS
1124 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001125 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001126 return RedCG.getSharedLValue(Count).getAddress();
1127 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001128 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1130 ConvertTypeForMem(RHSVD->getType()),
1131 "rhs.begin");
1132 });
1133 } else {
1134 QualType Type = PrivateVD->getType();
1135 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1136 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1137 // Store the address of the original variable associated with the LHS
1138 // implicit variable.
1139 if (IsArray) {
1140 OriginalAddr = Builder.CreateElementBitCast(
1141 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1142 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001143 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001144 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001145 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001146 return IsArray
1147 ? Builder.CreateElementBitCast(
1148 GetAddrOfLocalVar(PrivateVD),
1149 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1150 : GetAddrOfLocalVar(PrivateVD);
1151 });
1152 }
1153 ++ILHS;
1154 ++IRHS;
1155 ++IPriv;
1156 ++Count;
1157 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158}
1159
1160void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001161 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001162 if (!HaveInsertPoint())
1163 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001164 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 llvm::SmallVector<const Expr *, 8> LHSExprs;
1166 llvm::SmallVector<const Expr *, 8> RHSExprs;
1167 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001168 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001169 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001170 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001171 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001172 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1173 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1174 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1175 }
1176 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001177 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1178 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001179 ReductionKind == OMPD_simd;
1180 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001181 // Emit nowait reduction if nowait clause is present or directive is a
1182 // parallel directive (it always has implicit barrier).
1183 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001184 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001185 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001186 }
1187}
1188
Alexey Bataev61205072016-03-02 04:57:40 +00001189static void emitPostUpdateForReductionClause(
1190 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001191 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001192 if (!CGF.HaveInsertPoint())
1193 return;
1194 llvm::BasicBlock *DoneBB = nullptr;
1195 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001196 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001197 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001198 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001199 // If the first post-update expression is found, emit conditional
1200 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001201 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001202 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1203 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1204 CGF.EmitBlock(ThenBB);
1205 }
1206 }
1207 CGF.EmitIgnoredExpr(PostUpdate);
1208 }
1209 }
1210 if (DoneBB)
1211 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1212}
1213
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001214namespace {
1215/// Codegen lambda for appending distribute lower and upper bounds to outlined
1216/// parallel function. This is necessary for combined constructs such as
1217/// 'distribute parallel for'
1218typedef llvm::function_ref<void(CodeGenFunction &,
1219 const OMPExecutableDirective &,
1220 llvm::SmallVectorImpl<llvm::Value *> &)>
1221 CodeGenBoundParametersTy;
1222} // anonymous namespace
1223
1224static void emitCommonOMPParallelDirective(
1225 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1226 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1227 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001228 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001229 llvm::Value *OutlinedFn =
1230 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1231 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001232 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001233 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001234 llvm::Value *NumThreads =
1235 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1236 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001237 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001238 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001239 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001240 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001241 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001242 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001243 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001244 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001245 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001246 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1247 if (C->getNameModifier() == OMPD_unknown ||
1248 C->getNameModifier() == OMPD_parallel) {
1249 IfCond = C->getCondition();
1250 break;
1251 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001252 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001253
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001254 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001255 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001256 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1257 // lower and upper bounds with the pragma 'for' chunking mechanism.
1258 // The following lambda takes care of appending the lower and upper bound
1259 // parameters when necessary
1260 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001261 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001262 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001263 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264}
1265
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001266static void emitEmptyBoundParameters(CodeGenFunction &,
1267 const OMPExecutableDirective &,
1268 llvm::SmallVectorImpl<llvm::Value *> &) {}
1269
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001270void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001271 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001272 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001273 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001274 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001275 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001276 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1277 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001278 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001279 // propagation master's thread values of threadprivate variables to local
1280 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001281 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001282 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001283 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001284 }
1285 CGF.EmitOMPPrivateClause(S, PrivateScope);
1286 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1287 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001288 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001289 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001290 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001291 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1292 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001293 emitPostUpdateForReductionClause(*this, S,
1294 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001295}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001296
Alexey Bataev0f34da12015-07-02 04:17:07 +00001297void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1298 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001299 RunCleanupsScope BodyScope(*this);
1300 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001301 for (const Expr *UE : D.updates())
1302 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001303 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001304 // In distribute directives only loop counters may be marked as linear, no
1305 // need to generate the code for them.
1306 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1307 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001308 for (const Expr *UE : C->updates())
1309 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001310 }
Alexander Musman3276a272015-03-21 10:12:56 +00001311 }
1312
Alexander Musmana5f070a2014-10-01 06:03:56 +00001313 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001314 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001315 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001316 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001317 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001318 // The end (updates/cleanups).
1319 EmitBlock(Continue.getBlock());
1320 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001321}
1322
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323void CodeGenFunction::EmitOMPInnerLoop(
1324 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1325 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001326 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1327 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001328 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001329
1330 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001331 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001332 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001333 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001334 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1335 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336
1337 // If there are any cleanups between here and the loop-exit scope,
1338 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001339 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001340 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001341 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001342
Alexey Bataevddf3db92018-04-13 17:31:06 +00001343 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001344
Alexey Bataev2df54a02015-03-12 08:53:29 +00001345 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001346 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001347 if (ExitBlock != LoopExit.getBlock()) {
1348 EmitBlock(ExitBlock);
1349 EmitBranchThroughCleanup(LoopExit);
1350 }
1351
1352 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001353 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001354
1355 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001356 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001357 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1358
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001359 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001360
1361 // Emit "IV = IV + 1" and a back-edge to the condition block.
1362 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001363 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001364 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001365 BreakContinueStack.pop_back();
1366 EmitBranch(CondBlock);
1367 LoopStack.pop();
1368 // Emit the fall-through block.
1369 EmitBlock(LoopExit.getBlock());
1370}
1371
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001372bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001373 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001374 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001375 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001376 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001377 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001378 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001379 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001380 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1381 if (const auto *Ref =
1382 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001383 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001384 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001385 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001386 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1387 VD->getInit()->getType(), VK_LValue,
1388 VD->getInit()->getExprLoc());
1389 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1390 VD->getType()),
1391 /*capturedByInit=*/false);
1392 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001393 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001394 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001395 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001396 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001397 // Emit the linear steps for the linear clauses.
1398 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001399 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1400 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001401 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001402 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001403 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001404 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001405 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001406 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001407}
1408
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409void CodeGenFunction::EmitOMPLinearClauseFinal(
1410 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001411 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001413 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001414 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001415 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001416 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001417 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001418 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001419 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001420 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001421 // If the first post-update expression is found, emit conditional
1422 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001423 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 DoneBB = createBasicBlock(".omp.linear.pu.done");
1425 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1426 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001427 }
1428 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001429 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001430 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001431 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001432 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 Address OrigAddr = EmitLValue(&DRE).getAddress();
1434 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001435 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001436 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001437 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001438 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001439 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001440 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001441 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001442 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001443 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001444 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001445}
1446
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001447static void emitAlignedClause(CodeGenFunction &CGF,
1448 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001449 if (!CGF.HaveInsertPoint())
1450 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001451 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001452 unsigned ClauseAlignment = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001453 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1454 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001455 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1456 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001457 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001458 for (const Expr *E : Clause->varlists()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001459 unsigned Alignment = ClauseAlignment;
1460 if (Alignment == 0) {
1461 // OpenMP [2.8.1, Description]
1462 // If no optional parameter is specified, implementation-defined default
1463 // alignments for SIMD instructions on the target platforms are assumed.
1464 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001465 CGF.getContext()
1466 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1467 E->getType()->getPointeeType()))
1468 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001469 }
1470 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1471 "alignment is not power of 2");
1472 if (Alignment != 0) {
1473 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001474 CGF.EmitAlignmentAssumption(
1475 PtrValue, E, /*No second loc needed*/ SourceLocation(), Alignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001476 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001477 }
1478 }
1479}
1480
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001481void CodeGenFunction::EmitOMPPrivateLoopCounters(
1482 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1483 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001484 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001485 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001486 for (const Expr *E : S.counters()) {
1487 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1488 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001489 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001490 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001491 EmitAutoVarCleanups(VarEmission);
1492 LocalDeclMap.erase(PrivateVD);
1493 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1494 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001495 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001496 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1497 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001498 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001499 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001500 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1501 E->getType(), VK_LValue, E->getExprLoc());
1502 return EmitLValue(&DRE).getAddress();
1503 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001504 } else {
1505 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1506 return VarEmission.getAllocatedAddress();
1507 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001508 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001509 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001510 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001511 // Privatize extra loop counters used in loops for ordered(n) clauses.
1512 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1513 if (!C->getNumForLoops())
1514 continue;
1515 for (unsigned I = S.getCollapsedNumber(),
1516 E = C->getLoopNumIterations().size();
1517 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001518 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001519 const auto *VD = cast<VarDecl>(DRE->getDecl());
1520 // Override only those variables that are really emitted already.
1521 if (LocalDeclMap.count(VD)) {
1522 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1523 return CreateMemTemp(DRE->getType(), VD->getName());
1524 });
1525 }
1526 }
1527 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001528}
1529
Alexey Bataev62dbb972015-04-22 11:59:37 +00001530static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1531 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1532 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001533 if (!CGF.HaveInsertPoint())
1534 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001535 {
1536 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001537 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001538 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001539 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001540 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001541 CGF.EmitIgnoredExpr(I);
1542 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001543 }
1544 // Check that loop is executed at least one time.
1545 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1546}
1547
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001548void CodeGenFunction::EmitOMPLinearClause(
1549 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1550 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001551 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001552 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1553 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001554 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1555 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001556 SIMDLCVs.insert(
1557 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1558 }
1559 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001560 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001561 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001562 for (const Expr *E : C->varlists()) {
1563 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1564 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001565 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001566 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001567 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001568 // Emit private VarDecl with copy init.
1569 EmitVarDecl(*PrivateVD);
1570 return GetAddrOfLocalVar(PrivateVD);
1571 });
1572 assert(IsRegistered && "linear var already registered as private");
1573 // Silence the warning about unused variable.
1574 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001575 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001576 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001577 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001578 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001579 }
1580 }
1581}
1582
Alexey Bataev45bfad52015-08-21 12:19:04 +00001583static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001584 const OMPExecutableDirective &D,
1585 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001586 if (!CGF.HaveInsertPoint())
1587 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001588 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001589 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1590 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001591 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001592 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1593 // In presence of finite 'safelen', it may be unsafe to mark all
1594 // the memory instructions parallel, because loop-carried
1595 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001596 if (!IsMonotonic)
1597 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001598 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001599 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1600 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001601 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001602 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001603 // In presence of finite 'safelen', it may be unsafe to mark all
1604 // the memory instructions parallel, because loop-carried
1605 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001606 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001607 }
1608}
1609
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001610void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1611 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001612 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001613 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001614 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001615 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001616}
1617
Alexey Bataevef549a82016-03-09 09:49:09 +00001618void CodeGenFunction::EmitOMPSimdFinal(
1619 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001620 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001621 if (!HaveInsertPoint())
1622 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001623 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001624 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001625 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001626 for (const Expr *F : D.finals()) {
1627 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1628 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1629 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001630 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1631 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001632 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001633 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001634 // If the first post-update expression is found, emit conditional
1635 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001636 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001637 DoneBB = createBasicBlock(".omp.final.done");
1638 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1639 EmitBlock(ThenBB);
1640 }
1641 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001642 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001643 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001644 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001645 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001646 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001647 /*RefersToEnclosingVariableOrCapture=*/false,
1648 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1649 OrigAddr = EmitLValue(&DRE).getAddress();
1650 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001651 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001652 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001653 (void)VarScope.Privatize();
1654 EmitIgnoredExpr(F);
1655 }
1656 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001657 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001658 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001659 if (DoneBB)
1660 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001661}
1662
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001663static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1664 const OMPLoopDirective &S,
1665 CodeGenFunction::JumpDest LoopExit) {
1666 CGF.EmitOMPLoopBody(S, LoopExit);
1667 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001668}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001669
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001670/// Emit a helper variable and return corresponding lvalue.
1671static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1672 const DeclRefExpr *Helper) {
1673 auto VDecl = cast<VarDecl>(Helper->getDecl());
1674 CGF.EmitVarDecl(*VDecl);
1675 return CGF.EmitLValue(Helper);
1676}
1677
Alexey Bataevf8365372017-11-17 17:57:25 +00001678static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1679 PrePostActionTy &Action) {
1680 Action.Enter(CGF);
1681 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1682 "Expected simd directive");
1683 OMPLoopScope PreInitScope(CGF, S);
1684 // if (PreCond) {
1685 // for (IV in 0..LastIteration) BODY;
1686 // <Final counter/linear vars updates>;
1687 // }
1688 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001689 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1690 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1691 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1692 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1693 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1694 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001695
Alexey Bataevf8365372017-11-17 17:57:25 +00001696 // Emit: if (PreCond) - begin.
1697 // If the condition constant folds and can be elided, avoid emitting the
1698 // whole loop.
1699 bool CondConstant;
1700 llvm::BasicBlock *ContBlock = nullptr;
1701 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1702 if (!CondConstant)
1703 return;
1704 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001705 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001706 ContBlock = CGF.createBasicBlock("simd.if.end");
1707 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1708 CGF.getProfileCount(&S));
1709 CGF.EmitBlock(ThenBlock);
1710 CGF.incrementProfileCounter(&S);
1711 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001712
Alexey Bataevf8365372017-11-17 17:57:25 +00001713 // Emit the loop iteration variable.
1714 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001715 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001716 CGF.EmitVarDecl(*IVDecl);
1717 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001718
Alexey Bataevf8365372017-11-17 17:57:25 +00001719 // Emit the iterations count variable.
1720 // If it is not a variable, Sema decided to calculate iterations count on
1721 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001722 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001723 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1724 // Emit calculation of the iterations count.
1725 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1726 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001727
Alexey Bataevf8365372017-11-17 17:57:25 +00001728 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001729
Alexey Bataevf8365372017-11-17 17:57:25 +00001730 emitAlignedClause(CGF, S);
1731 (void)CGF.EmitOMPLinearClauseInit(S);
1732 {
1733 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1734 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1735 CGF.EmitOMPLinearClause(S, LoopScope);
1736 CGF.EmitOMPPrivateClause(S, LoopScope);
1737 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1738 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1739 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001740 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1741 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevf8365372017-11-17 17:57:25 +00001742 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1743 S.getInc(),
1744 [&S](CodeGenFunction &CGF) {
1745 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1746 CGF.EmitStopPoint(&S);
1747 },
1748 [](CodeGenFunction &) {});
Alexey Bataevddf3db92018-04-13 17:31:06 +00001749 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001750 // Emit final copy of the lastprivate variables at the end of loops.
1751 if (HasLastprivateClause)
1752 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1753 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001754 emitPostUpdateForReductionClause(CGF, S,
1755 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001756 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001757 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001758 // Emit: if (PreCond) - end.
1759 if (ContBlock) {
1760 CGF.EmitBranch(ContBlock);
1761 CGF.EmitBlock(ContBlock, true);
1762 }
1763}
1764
1765void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1766 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1767 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001768 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001769 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001770 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001771}
1772
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001773void CodeGenFunction::EmitOMPOuterLoop(
1774 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1775 CodeGenFunction::OMPPrivateScope &LoopScope,
1776 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1777 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1778 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001779 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001780
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001781 const Expr *IVExpr = S.getIterationVariable();
1782 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1783 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1784
Alexey Bataevddf3db92018-04-13 17:31:06 +00001785 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001786
1787 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001788 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001789 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001790 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001791 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1792 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001793
1794 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001795 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001796 // UB = min(UB, GlobalUB) or
1797 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1798 // 'distribute parallel for')
1799 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001800 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001801 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001802 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001803 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001804 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001805 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001806 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001807 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001808 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001809
1810 // If there are any cleanups between here and the loop-exit scope,
1811 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001812 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001813 if (LoopScope.requiresCleanups())
1814 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1815
Alexey Bataevddf3db92018-04-13 17:31:06 +00001816 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001817 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1818 if (ExitBlock != LoopExit.getBlock()) {
1819 EmitBlock(ExitBlock);
1820 EmitBranchThroughCleanup(LoopExit);
1821 }
1822 EmitBlock(LoopBody);
1823
Alexander Musman92bdaab2015-03-12 13:37:50 +00001824 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1825 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001826 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001827 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001828
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001829 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001830 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001831 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1832
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001833 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1834 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001835 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1836 LoopStack.setParallel(!IsMonotonic);
1837 else
1838 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001839
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001840 SourceLocation Loc = S.getBeginLoc();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001841
1842 // when 'distribute' is not combined with a 'for':
1843 // while (idx <= UB) { BODY; ++idx; }
1844 // when 'distribute' is combined with a 'for'
1845 // (e.g. 'distribute parallel for')
1846 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1847 EmitOMPInnerLoop(
1848 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1849 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1850 CodeGenLoop(CGF, S, LoopExit);
1851 },
1852 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1853 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1854 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001855
1856 EmitBlock(Continue.getBlock());
1857 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001858 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001859 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001860 EmitIgnoredExpr(LoopArgs.NextLB);
1861 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001862 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001863
1864 EmitBranch(CondBlock);
1865 LoopStack.pop();
1866 // Emit the fall-through block.
1867 EmitBlock(LoopExit.getBlock());
1868
1869 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001870 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1871 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001872 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00001873 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001874 };
1875 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001876}
1877
1878void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001879 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001880 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001881 const OMPLoopArguments &LoopArgs,
1882 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001883 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001884
1885 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001886 const bool DynamicOrOrdered =
1887 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001888
1889 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001890 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001891 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001892 "static non-chunked schedule does not need outer loop");
1893
1894 // Emit outer loop.
1895 //
1896 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1897 // When schedule(dynamic,chunk_size) is specified, the iterations are
1898 // distributed to threads in the team in chunks as the threads request them.
1899 // Each thread executes a chunk of iterations, then requests another chunk,
1900 // until no chunks remain to be distributed. Each chunk contains chunk_size
1901 // iterations, except for the last chunk to be distributed, which may have
1902 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1903 //
1904 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1905 // to threads in the team in chunks as the executing threads request them.
1906 // Each thread executes a chunk of iterations, then requests another chunk,
1907 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1908 // each chunk is proportional to the number of unassigned iterations divided
1909 // by the number of threads in the team, decreasing to 1. For a chunk_size
1910 // with value k (greater than 1), the size of each chunk is determined in the
1911 // same way, with the restriction that the chunks do not contain fewer than k
1912 // iterations (except for the last chunk to be assigned, which may have fewer
1913 // than k iterations).
1914 //
1915 // When schedule(auto) is specified, the decision regarding scheduling is
1916 // delegated to the compiler and/or runtime system. The programmer gives the
1917 // implementation the freedom to choose any possible mapping of iterations to
1918 // threads in the team.
1919 //
1920 // When schedule(runtime) is specified, the decision regarding scheduling is
1921 // deferred until run time, and the schedule and chunk size are taken from the
1922 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1923 // implementation defined
1924 //
1925 // while(__kmpc_dispatch_next(&LB, &UB)) {
1926 // idx = LB;
1927 // while (idx <= UB) { BODY; ++idx;
1928 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1929 // } // inner loop
1930 // }
1931 //
1932 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1933 // When schedule(static, chunk_size) is specified, iterations are divided into
1934 // chunks of size chunk_size, and the chunks are assigned to the threads in
1935 // the team in a round-robin fashion in the order of the thread number.
1936 //
1937 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1938 // while (idx <= UB) { BODY; ++idx; } // inner loop
1939 // LB = LB + ST;
1940 // UB = UB + ST;
1941 // }
1942 //
1943
1944 const Expr *IVExpr = S.getIterationVariable();
1945 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1946 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1947
1948 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001949 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
1950 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001951 llvm::Value *LBVal = DispatchBounds.first;
1952 llvm::Value *UBVal = DispatchBounds.second;
1953 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1954 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001955 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001956 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001957 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001958 CGOpenMPRuntime::StaticRTInput StaticInit(
1959 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1960 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001961 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001962 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001963 }
1964
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001965 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1966 const unsigned IVSize,
1967 const bool IVSigned) {
1968 if (Ordered) {
1969 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1970 IVSigned);
1971 }
1972 };
1973
1974 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1975 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1976 OuterLoopArgs.IncExpr = S.getInc();
1977 OuterLoopArgs.Init = S.getInit();
1978 OuterLoopArgs.Cond = S.getCond();
1979 OuterLoopArgs.NextLB = S.getNextLowerBound();
1980 OuterLoopArgs.NextUB = S.getNextUpperBound();
1981 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1982 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001983}
1984
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001985static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1986 const unsigned IVSize, const bool IVSigned) {}
1987
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001988void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001989 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1990 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1991 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001992
Alexey Bataevddf3db92018-04-13 17:31:06 +00001993 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001994
1995 // Emit outer loop.
1996 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1997 // dynamic
1998 //
1999
2000 const Expr *IVExpr = S.getIterationVariable();
2001 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2002 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2003
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002004 CGOpenMPRuntime::StaticRTInput StaticInit(
2005 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2006 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002007 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002008
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002009 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002010 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002011 Expr *IncExpr;
2012 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2013 IncExpr = S.getDistInc();
2014 else
2015 IncExpr = S.getInc();
2016
2017 // this routine is shared by 'omp distribute parallel for' and
2018 // 'omp distribute': select the right EUB expression depending on the
2019 // directive
2020 OMPLoopArguments OuterLoopArgs;
2021 OuterLoopArgs.LB = LoopArgs.LB;
2022 OuterLoopArgs.UB = LoopArgs.UB;
2023 OuterLoopArgs.ST = LoopArgs.ST;
2024 OuterLoopArgs.IL = LoopArgs.IL;
2025 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2026 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2027 ? S.getCombinedEnsureUpperBound()
2028 : S.getEnsureUpperBound();
2029 OuterLoopArgs.IncExpr = IncExpr;
2030 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2031 ? S.getCombinedInit()
2032 : S.getInit();
2033 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2034 ? S.getCombinedCond()
2035 : S.getCond();
2036 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2037 ? S.getCombinedNextLowerBound()
2038 : S.getNextLowerBound();
2039 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2040 ? S.getCombinedNextUpperBound()
2041 : S.getNextUpperBound();
2042
2043 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2044 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2045 emitEmptyOrdered);
2046}
2047
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002048static std::pair<LValue, LValue>
2049emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2050 const OMPExecutableDirective &S) {
2051 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2052 LValue LB =
2053 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2054 LValue UB =
2055 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2056
2057 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2058 // parallel for') we need to use the 'distribute'
2059 // chunk lower and upper bounds rather than the whole loop iteration
2060 // space. These are parameters to the outlined function for 'parallel'
2061 // and we copy the bounds of the previous schedule into the
2062 // the current ones.
2063 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2064 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002065 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2066 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002067 PrevLBVal = CGF.EmitScalarConversion(
2068 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002069 LS.getIterationVariable()->getType(),
2070 LS.getPrevLowerBoundVariable()->getExprLoc());
2071 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2072 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002073 PrevUBVal = CGF.EmitScalarConversion(
2074 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002075 LS.getIterationVariable()->getType(),
2076 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002077
2078 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2079 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2080
2081 return {LB, UB};
2082}
2083
2084/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2085/// we need to use the LB and UB expressions generated by the worksharing
2086/// code generation support, whereas in non combined situations we would
2087/// just emit 0 and the LastIteration expression
2088/// This function is necessary due to the difference of the LB and UB
2089/// types for the RT emission routines for 'for_static_init' and
2090/// 'for_dispatch_init'
2091static std::pair<llvm::Value *, llvm::Value *>
2092emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2093 const OMPExecutableDirective &S,
2094 Address LB, Address UB) {
2095 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2096 const Expr *IVExpr = LS.getIterationVariable();
2097 // when implementing a dynamic schedule for a 'for' combined with a
2098 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2099 // is not normalized as each team only executes its own assigned
2100 // distribute chunk
2101 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002102 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002103 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002104 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002105 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002106 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002107}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002108
2109static void emitDistributeParallelForDistributeInnerBoundParams(
2110 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2111 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2112 const auto &Dir = cast<OMPLoopDirective>(S);
2113 LValue LB =
2114 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002115 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2117 CapturedVars.push_back(LBCast);
2118 LValue UB =
2119 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2120
Alexey Bataevddf3db92018-04-13 17:31:06 +00002121 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002122 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2123 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002124}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002125
2126static void
2127emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2128 const OMPLoopDirective &S,
2129 CodeGenFunction::JumpDest LoopExit) {
2130 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002131 PrePostActionTy &Action) {
2132 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002133 bool HasCancel = false;
2134 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2135 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2136 HasCancel = D->hasCancel();
2137 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2138 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002139 else if (const auto *D =
2140 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2141 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002142 }
2143 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2144 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002145 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2146 emitDistributeParallelForInnerBounds,
2147 emitDistributeParallelForDispatchBounds);
2148 };
2149
2150 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002151 CGF, S,
2152 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2153 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002154 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002155}
2156
Carlo Bertolli9925f152016-06-27 14:55:37 +00002157void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2158 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002159 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2160 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2161 S.getDistInc());
2162 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002163 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002164 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002165}
2166
Kelvin Li4a39add2016-07-05 05:00:15 +00002167void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2168 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002169 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2170 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2171 S.getDistInc());
2172 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002173 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002174 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002175}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002176
2177void CodeGenFunction::EmitOMPDistributeSimdDirective(
2178 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002179 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2180 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2181 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002182 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002183 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002184}
2185
Alexey Bataevf8365372017-11-17 17:57:25 +00002186void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2187 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2188 // Emit SPMD target parallel for region as a standalone region.
2189 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2190 emitOMPSimdRegion(CGF, S, Action);
2191 };
2192 llvm::Function *Fn;
2193 llvm::Constant *Addr;
2194 // Emit target region as a standalone region.
2195 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2196 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2197 assert(Fn && Addr && "Target device function emission failed.");
2198}
2199
Kelvin Li986330c2016-07-20 22:57:10 +00002200void CodeGenFunction::EmitOMPTargetSimdDirective(
2201 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002202 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2203 emitOMPSimdRegion(CGF, S, Action);
2204 };
2205 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002206}
2207
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002208namespace {
2209 struct ScheduleKindModifiersTy {
2210 OpenMPScheduleClauseKind Kind;
2211 OpenMPScheduleClauseModifier M1;
2212 OpenMPScheduleClauseModifier M2;
2213 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2214 OpenMPScheduleClauseModifier M1,
2215 OpenMPScheduleClauseModifier M2)
2216 : Kind(Kind), M1(M1), M2(M2) {}
2217 };
2218} // namespace
2219
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002220bool CodeGenFunction::EmitOMPWorksharingLoop(
2221 const OMPLoopDirective &S, Expr *EUB,
2222 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2223 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002224 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002225 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2226 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002227 EmitVarDecl(*IVDecl);
2228
2229 // Emit the iterations count variable.
2230 // If it is not a variable, Sema decided to calculate iterations count on each
2231 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002232 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002233 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2234 // Emit calculation of the iterations count.
2235 EmitIgnoredExpr(S.getCalcLastIteration());
2236 }
2237
Alexey Bataevddf3db92018-04-13 17:31:06 +00002238 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002239
Alexey Bataev38e89532015-04-16 04:54:05 +00002240 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002241 // Check pre-condition.
2242 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002243 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002244 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002245 // If the condition constant folds and can be elided, avoid emitting the
2246 // whole loop.
2247 bool CondConstant;
2248 llvm::BasicBlock *ContBlock = nullptr;
2249 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2250 if (!CondConstant)
2251 return false;
2252 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002253 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002254 ContBlock = createBasicBlock("omp.precond.end");
2255 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002256 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002257 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002258 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002259 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002260
Alexey Bataevea33dee2018-02-15 23:39:43 +00002261 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002262 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002263 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002264 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002265 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002266 else
2267 Ordered = true;
2268 }
2269
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002270 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002271 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002272 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002273 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002274
2275 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2276 LValue LB = Bounds.first;
2277 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002278 LValue ST =
2279 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2280 LValue IL =
2281 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2282
Alexander Musmanc6388682014-12-15 07:07:06 +00002283 // Emit 'then' code.
2284 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002285 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002286 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002287 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002288 // initialization of firstprivate variables and post-update of
2289 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002290 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002291 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002292 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002293 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002294 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002295 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002296 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002297 EmitOMPPrivateLoopCounters(S, LoopScope);
2298 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002299 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002300 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2301 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002302
2303 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002304 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002305 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002306 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002307 ScheduleKind.Schedule = C->getScheduleKind();
2308 ScheduleKind.M1 = C->getFirstScheduleModifier();
2309 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002310 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002311 } else {
2312 // Default behaviour for schedule clause.
2313 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002314 *this, S, ScheduleKind.Schedule, ChunkExpr);
2315 }
2316 bool HasChunkSizeOne = false;
2317 llvm::Value *Chunk = nullptr;
2318 if (ChunkExpr) {
2319 Chunk = EmitScalarExpr(ChunkExpr);
2320 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2321 S.getIterationVariable()->getType(),
2322 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002323 Expr::EvalResult Result;
2324 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2325 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002326 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002327 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002328 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002329 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2330 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002331 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2332 // If the static schedule kind is specified or if the ordered clause is
2333 // specified, and if no monotonic modifier is specified, the effect will
2334 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002335 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2336 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2337 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2338 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2339 /* Chunked */ Chunk != nullptr) ||
2340 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002341 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002342 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2343 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002344 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2345 // When no chunk_size is specified, the iteration space is divided into
2346 // chunks that are approximately equal in size, and at most one chunk is
2347 // distributed to each thread. Note that the size of the chunks is
2348 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002349 CGOpenMPRuntime::StaticRTInput StaticInit(
2350 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002351 UB.getAddress(), ST.getAddress(),
2352 StaticChunkedOne ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002353 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002354 ScheduleKind, StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002355 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002356 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002357 // UB = min(UB, GlobalUB);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002358 if (!StaticChunkedOne)
2359 EmitIgnoredExpr(S.getEnsureUpperBound());
Alexander Musmanc6388682014-12-15 07:07:06 +00002360 // IV = LB;
2361 EmitIgnoredExpr(S.getInit());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002362 // For unchunked static schedule generate:
2363 //
2364 // while (idx <= UB) {
2365 // BODY;
2366 // ++idx;
2367 // }
2368 //
2369 // For static schedule with chunk one:
2370 //
2371 // while (IV <= PrevUB) {
2372 // BODY;
2373 // IV += ST;
2374 // }
2375 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
2376 StaticChunkedOne ? S.getCombinedParForInDistCond() : S.getCond(),
2377 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2378 [&S, LoopExit](CodeGenFunction &CGF) {
2379 CGF.EmitOMPLoopBody(S, LoopExit);
2380 CGF.EmitStopPoint(&S);
2381 },
2382 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002383 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002384 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002385 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002386 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002387 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002388 };
2389 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002390 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002391 const bool IsMonotonic =
2392 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2393 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2394 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2395 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002396 // Emit the outer loop, which requests its work chunk [LB..UB] from
2397 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002398 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2399 ST.getAddress(), IL.getAddress(),
2400 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002401 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002402 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002403 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002404 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002405 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2406 return CGF.Builder.CreateIsNotNull(
2407 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2408 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002409 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002410 EmitOMPReductionClauseFinal(
2411 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2412 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2413 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002414 // Emit post-update of the reduction variables if IsLastIter != 0.
2415 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002416 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002417 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002418 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002419 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002420 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2421 if (HasLastprivateClause)
2422 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002423 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002424 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002425 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002426 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002427 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002428 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002429 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002430 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002431 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002432 if (ContBlock) {
2433 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002434 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002435 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002436 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002437 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002438}
2439
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002440/// The following two functions generate expressions for the loop lower
2441/// and upper bounds in case of static and dynamic (dispatch) schedule
2442/// of the associated 'for' or 'distribute' loop.
2443static std::pair<LValue, LValue>
2444emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002445 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002446 LValue LB =
2447 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2448 LValue UB =
2449 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2450 return {LB, UB};
2451}
2452
2453/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2454/// consider the lower and upper bound expressions generated by the
2455/// worksharing loop support, but we use 0 and the iteration space size as
2456/// constants
2457static std::pair<llvm::Value *, llvm::Value *>
2458emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2459 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002460 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002461 const Expr *IVExpr = LS.getIterationVariable();
2462 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2463 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2464 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2465 return {LBVal, UBVal};
2466}
2467
Alexander Musmanc6388682014-12-15 07:07:06 +00002468void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002469 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002470 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2471 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002472 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002473 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2474 emitForLoopBounds,
2475 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002476 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002477 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002478 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002479 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2480 S.hasCancel());
2481 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002482
2483 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002484 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002485 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002486}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002487
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002488void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002489 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002490 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2491 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002492 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2493 emitForLoopBounds,
2494 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002495 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002496 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002497 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002498 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2499 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002500
2501 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002502 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002503 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002504}
2505
Alexey Bataev2df54a02015-03-12 08:53:29 +00002506static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2507 const Twine &Name,
2508 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002509 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002510 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002511 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002512 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002513}
2514
Alexey Bataev3392d762016-02-16 11:18:12 +00002515void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002516 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2517 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002518 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002519 auto &&CodeGen = [&S, CapturedStmt, CS,
2520 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2521 ASTContext &C = CGF.getContext();
2522 QualType KmpInt32Ty =
2523 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002524 // Emit helper vars inits.
2525 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2526 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002527 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2528 ? CGF.Builder.getInt32(CS->size() - 1)
2529 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002530 LValue UB =
2531 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2532 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2533 CGF.Builder.getInt32(1));
2534 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2535 CGF.Builder.getInt32(0));
2536 // Loop counter.
2537 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002538 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002539 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002540 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002541 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2542 // Generate condition for loop.
2543 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002544 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002545 // Increment for loop counter.
2546 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002547 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002548 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002549 // Iterate through all sections and emit a switch construct:
2550 // switch (IV) {
2551 // case 0:
2552 // <SectionStmt[0]>;
2553 // break;
2554 // ...
2555 // case <NumSection> - 1:
2556 // <SectionStmt[<NumSection> - 1]>;
2557 // break;
2558 // }
2559 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002560 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2561 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002562 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002563 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002564 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002565 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002566 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002567 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2568 CGF.EmitBlock(CaseBB);
2569 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002570 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002571 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002572 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002573 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002574 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002575 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002576 CGF.EmitBlock(CaseBB);
2577 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002578 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002579 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002580 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002581 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002582 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002583
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002584 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2585 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002586 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002587 // initialization of firstprivate variables and post-update of lastprivate
2588 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002589 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002590 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002591 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002592 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002593 CGF.EmitOMPPrivateClause(S, LoopScope);
2594 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2595 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2596 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002597 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2598 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002599
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002600 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002601 OpenMPScheduleTy ScheduleKind;
2602 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002603 CGOpenMPRuntime::StaticRTInput StaticInit(
2604 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2605 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002606 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002607 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002608 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002609 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002610 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002611 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2612 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2613 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002614 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002615 // while (idx <= UB) { BODY; ++idx; }
2616 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2617 [](CodeGenFunction &) {});
2618 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002619 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002620 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002621 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002622 };
2623 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002624 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002625 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002626 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2627 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002628 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002629 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002630
2631 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2632 if (HasLastprivates)
2633 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002634 S, /*NoFinals=*/false,
2635 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002636 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002637 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002638
2639 bool HasCancel = false;
2640 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2641 HasCancel = OSD->hasCancel();
2642 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2643 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002644 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002645 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2646 HasCancel);
2647 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2648 // clause. Otherwise the barrier will be generated by the codegen for the
2649 // directive.
2650 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002651 // Emit implicit barrier to synchronize threads and avoid data races on
2652 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002653 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002654 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002655 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002656}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002657
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002658void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002659 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002660 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002661 EmitSections(S);
2662 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002663 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002664 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002665 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002666 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002667 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002668}
2669
2670void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002671 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002672 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002673 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002674 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002675 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2676 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002677}
2678
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002679void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002681 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002682 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002683 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002684 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002685 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002686 // Build a list of copyprivate variables along with helper expressions
2687 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002688 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002689 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002690 DestExprs.append(C->destination_exprs().begin(),
2691 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002692 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002693 AssignmentOps.append(C->assignment_ops().begin(),
2694 C->assignment_ops().end());
2695 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002696 // Emit code for 'single' region along with 'copyprivate' clauses
2697 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2698 Action.Enter(CGF);
2699 OMPPrivateScope SingleScope(CGF);
2700 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2701 CGF.EmitOMPPrivateClause(S, SingleScope);
2702 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002703 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002704 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002705 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002706 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002707 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002708 CopyprivateVars, DestExprs,
2709 SrcExprs, AssignmentOps);
2710 }
2711 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2712 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002713 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002714 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002715 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002716 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002717 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002718}
2719
Alexey Bataev8d690652014-12-04 07:23:53 +00002720void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002721 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2722 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002723 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002724 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002725 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002726 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002727}
2728
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002729void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002730 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2731 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002732 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002733 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002734 const Expr *Hint = nullptr;
2735 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002736 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002737 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002738 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2739 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002740 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002741}
2742
Alexey Bataev671605e2015-04-13 05:28:11 +00002743void CodeGenFunction::EmitOMPParallelForDirective(
2744 const OMPParallelForDirective &S) {
2745 // Emit directive as a combined directive that consists of two implicit
2746 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002747 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2748 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002749 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002750 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2751 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002752 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002753 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2754 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002755}
2756
Alexander Musmane4e893b2014-09-23 09:33:00 +00002757void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002758 const OMPParallelForSimdDirective &S) {
2759 // Emit directive as a combined directive that consists of two implicit
2760 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002761 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2762 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002763 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2764 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002765 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002766 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2767 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002768}
2769
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002770void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002771 const OMPParallelSectionsDirective &S) {
2772 // Emit directive as a combined directive that consists of two implicit
2773 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002774 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2775 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002776 CGF.EmitSections(S);
2777 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002778 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2779 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002780}
2781
Alexey Bataev475a7442018-01-12 19:39:11 +00002782void CodeGenFunction::EmitOMPTaskBasedDirective(
2783 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2784 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2785 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002786 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002787 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002788 auto I = CS->getCapturedDecl()->param_begin();
2789 auto PartId = std::next(I);
2790 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002791 // Check if the task is final
2792 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2793 // If the condition constant folds and can be elided, try to avoid emitting
2794 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002795 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002796 bool CondConstant;
2797 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2798 Data.Final.setInt(CondConstant);
2799 else
2800 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2801 } else {
2802 // By default the task is not final.
2803 Data.Final.setInt(/*IntVal=*/false);
2804 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002805 // Check if the task has 'priority' clause.
2806 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002807 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002808 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002809 Data.Priority.setPointer(EmitScalarConversion(
2810 EmitScalarExpr(Prio), Prio->getType(),
2811 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2812 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002813 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002814 // The first function argument for tasks is a thread id, the second one is a
2815 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002816 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2817 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002818 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002819 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002820 for (const Expr *IInit : C->private_copies()) {
2821 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002822 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002823 Data.PrivateVars.push_back(*IRef);
2824 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002825 }
2826 ++IRef;
2827 }
2828 }
2829 EmittedAsPrivate.clear();
2830 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002831 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002832 auto IRef = C->varlist_begin();
2833 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002834 for (const Expr *IInit : C->private_copies()) {
2835 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002836 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002837 Data.FirstprivateVars.push_back(*IRef);
2838 Data.FirstprivateCopies.push_back(IInit);
2839 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002840 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002841 ++IRef;
2842 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002843 }
2844 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002845 // Get list of lastprivate variables (for taskloops).
2846 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2847 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2848 auto IRef = C->varlist_begin();
2849 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002850 for (const Expr *IInit : C->private_copies()) {
2851 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002852 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2853 Data.LastprivateVars.push_back(*IRef);
2854 Data.LastprivateCopies.push_back(IInit);
2855 }
2856 LastprivateDstsOrigs.insert(
2857 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2858 cast<DeclRefExpr>(*IRef)});
2859 ++IRef;
2860 ++ID;
2861 }
2862 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002863 SmallVector<const Expr *, 4> LHSs;
2864 SmallVector<const Expr *, 4> RHSs;
2865 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2866 auto IPriv = C->privates().begin();
2867 auto IRed = C->reduction_ops().begin();
2868 auto ILHS = C->lhs_exprs().begin();
2869 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002870 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002871 Data.ReductionVars.emplace_back(Ref);
2872 Data.ReductionCopies.emplace_back(*IPriv);
2873 Data.ReductionOps.emplace_back(*IRed);
2874 LHSs.emplace_back(*ILHS);
2875 RHSs.emplace_back(*IRHS);
2876 std::advance(IPriv, 1);
2877 std::advance(IRed, 1);
2878 std::advance(ILHS, 1);
2879 std::advance(IRHS, 1);
2880 }
2881 }
2882 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002883 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002884 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002885 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00002886 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00002887 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00002888 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2889 CapturedRegion](CodeGenFunction &CGF,
2890 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002891 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002892 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002893 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2894 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002895 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002896 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
2897 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
2898 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
2899 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00002900 // Map privates.
2901 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2902 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2903 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002904 for (const Expr *E : Data.PrivateVars) {
2905 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002906 Address PrivatePtr = CGF.CreateMemTemp(
2907 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002908 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002910 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002911 for (const Expr *E : Data.FirstprivateVars) {
2912 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002913 Address PrivatePtr =
2914 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2915 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002916 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002917 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002918 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002919 for (const Expr *E : Data.LastprivateVars) {
2920 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002921 Address PrivatePtr =
2922 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2923 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002924 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002925 CallArgs.push_back(PrivatePtr.getPointer());
2926 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002927 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00002928 CopyFn, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002929 for (const auto &Pair : LastprivateDstsOrigs) {
2930 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002931 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
2932 /*RefersToEnclosingVariableOrCapture=*/
2933 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
2934 Pair.second->getType(), VK_LValue,
2935 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002936 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2937 return CGF.EmitLValue(&DRE).getAddress();
2938 });
2939 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002940 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002941 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2942 CGF.getContext().getDeclAlign(Pair.first));
2943 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2944 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002945 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002946 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002947 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002948 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2949 Data.ReductionOps);
2950 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2951 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2952 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2953 RedCG.emitSharedLValue(CGF, Cnt);
2954 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002955 // FIXME: This must removed once the runtime library is fixed.
2956 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002957 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002958 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002959 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002960 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002961 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002962 Replacement =
2963 Address(CGF.EmitScalarConversion(
2964 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2965 CGF.getContext().getPointerType(
2966 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002967 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002968 Replacement.getAlignment());
2969 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2970 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2971 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002972 }
2973 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002974 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002975 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002976 SmallVector<const Expr *, 4> InRedVars;
2977 SmallVector<const Expr *, 4> InRedPrivs;
2978 SmallVector<const Expr *, 4> InRedOps;
2979 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2980 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2981 auto IPriv = C->privates().begin();
2982 auto IRed = C->reduction_ops().begin();
2983 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002984 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002985 InRedVars.emplace_back(Ref);
2986 InRedPrivs.emplace_back(*IPriv);
2987 InRedOps.emplace_back(*IRed);
2988 TaskgroupDescriptors.emplace_back(*ITD);
2989 std::advance(IPriv, 1);
2990 std::advance(IRed, 1);
2991 std::advance(ITD, 1);
2992 }
2993 }
2994 // Privatize in_reduction items here, because taskgroup descriptors must be
2995 // privatized earlier.
2996 OMPPrivateScope InRedScope(CGF);
2997 if (!InRedVars.empty()) {
2998 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2999 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3000 RedCG.emitSharedLValue(CGF, Cnt);
3001 RedCG.emitAggregateType(CGF, Cnt);
3002 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003003 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003004 // FIXME: This must removed once the runtime library is fixed.
3005 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003006 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003007 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003008 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003009 llvm::Value *ReductionsPtr =
3010 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3011 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003012 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003013 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003014 Replacement = Address(
3015 CGF.EmitScalarConversion(
3016 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3017 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003018 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003019 Replacement.getAlignment());
3020 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3021 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3022 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003023 }
3024 }
3025 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003026
3027 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003028 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003029 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003030 llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003031 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3032 Data.NumberOfParts);
3033 OMPLexicalScope Scope(*this, S);
3034 TaskGen(*this, OutlinedFn, Data);
3035}
3036
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003037static ImplicitParamDecl *
3038createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003039 QualType Ty, CapturedDecl *CD,
3040 SourceLocation Loc) {
3041 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3042 ImplicitParamDecl::Other);
3043 auto *OrigRef = DeclRefExpr::Create(
3044 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3045 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3046 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3047 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003048 auto *PrivateRef = DeclRefExpr::Create(
3049 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003050 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003051 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003052 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3053 ImplicitParamDecl::Other);
3054 auto *InitRef = DeclRefExpr::Create(
3055 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3056 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003057 PrivateVD->setInitStyle(VarDecl::CInit);
3058 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3059 InitRef, /*BasePath=*/nullptr,
3060 VK_RValue));
3061 Data.FirstprivateVars.emplace_back(OrigRef);
3062 Data.FirstprivateCopies.emplace_back(PrivateRef);
3063 Data.FirstprivateInits.emplace_back(InitRef);
3064 return OrigVD;
3065}
3066
3067void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3068 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3069 OMPTargetDataInfo &InputInfo) {
3070 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003071 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3072 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3073 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3074 auto I = CS->getCapturedDecl()->param_begin();
3075 auto PartId = std::next(I);
3076 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003077 OMPTaskDataTy Data;
3078 // The task is not final.
3079 Data.Final.setInt(/*IntVal=*/false);
3080 // Get list of firstprivate variables.
3081 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3082 auto IRef = C->varlist_begin();
3083 auto IElemInitRef = C->inits().begin();
3084 for (auto *IInit : C->private_copies()) {
3085 Data.FirstprivateVars.push_back(*IRef);
3086 Data.FirstprivateCopies.push_back(IInit);
3087 Data.FirstprivateInits.push_back(*IElemInitRef);
3088 ++IRef;
3089 ++IElemInitRef;
3090 }
3091 }
3092 OMPPrivateScope TargetScope(*this);
3093 VarDecl *BPVD = nullptr;
3094 VarDecl *PVD = nullptr;
3095 VarDecl *SVD = nullptr;
3096 if (InputInfo.NumberOfTargetItems > 0) {
3097 auto *CD = CapturedDecl::Create(
3098 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3099 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3100 QualType BaseAndPointersType = getContext().getConstantArrayType(
3101 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3102 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003103 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003104 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003105 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003106 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003107 QualType SizesType = getContext().getConstantArrayType(
3108 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3109 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003110 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003111 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003112 TargetScope.addPrivate(
3113 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3114 TargetScope.addPrivate(PVD,
3115 [&InputInfo]() { return InputInfo.PointersArray; });
3116 TargetScope.addPrivate(SVD,
3117 [&InputInfo]() { return InputInfo.SizesArray; });
3118 }
3119 (void)TargetScope.Privatize();
3120 // Build list of dependences.
3121 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003122 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003123 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003124 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3125 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3126 // Set proper addresses for generated private copies.
3127 OMPPrivateScope Scope(CGF);
3128 if (!Data.FirstprivateVars.empty()) {
3129 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003130 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3131 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3132 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3133 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003134 // Map privates.
3135 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3136 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3137 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003138 for (const Expr *E : Data.FirstprivateVars) {
3139 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003140 Address PrivatePtr =
3141 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3142 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003143 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003144 CallArgs.push_back(PrivatePtr.getPointer());
3145 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003146 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003147 CopyFn, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003148 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003149 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3150 CGF.getContext().getDeclAlign(Pair.first));
3151 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3152 }
3153 }
3154 // Privatize all private variables except for in_reduction items.
3155 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003156 if (InputInfo.NumberOfTargetItems > 0) {
3157 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3158 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3159 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3160 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3161 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3162 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3163 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003164
3165 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003166 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003167 BodyGen(CGF);
3168 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003169 llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003170 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3171 Data.NumberOfParts);
3172 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3173 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3174 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3175 SourceLocation());
3176
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003177 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003178 SharedsTy, CapturedStruct, &IfCond, Data);
3179}
3180
Alexey Bataev7292c292016-04-25 12:22:29 +00003181void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3182 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003183 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003184 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3185 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003186 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003187 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3188 if (C->getNameModifier() == OMPD_unknown ||
3189 C->getNameModifier() == OMPD_task) {
3190 IfCond = C->getCondition();
3191 break;
3192 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003193 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003194
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003195 OMPTaskDataTy Data;
3196 // Check if we should emit tied or untied task.
3197 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003198 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3199 CGF.EmitStmt(CS->getCapturedStmt());
3200 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003201 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003202 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003203 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003204 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003205 SharedsTy, CapturedStruct, IfCond,
3206 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003207 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003208 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003209}
3210
Alexey Bataev9f797f32015-02-05 05:57:51 +00003211void CodeGenFunction::EmitOMPTaskyieldDirective(
3212 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003213 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003214}
3215
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003216void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003217 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003218}
3219
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003220void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003221 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003222}
3223
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003224void CodeGenFunction::EmitOMPTaskgroupDirective(
3225 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003226 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3227 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003228 if (const Expr *E = S.getReductionRef()) {
3229 SmallVector<const Expr *, 4> LHSs;
3230 SmallVector<const Expr *, 4> RHSs;
3231 OMPTaskDataTy Data;
3232 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3233 auto IPriv = C->privates().begin();
3234 auto IRed = C->reduction_ops().begin();
3235 auto ILHS = C->lhs_exprs().begin();
3236 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003237 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003238 Data.ReductionVars.emplace_back(Ref);
3239 Data.ReductionCopies.emplace_back(*IPriv);
3240 Data.ReductionOps.emplace_back(*IRed);
3241 LHSs.emplace_back(*ILHS);
3242 RHSs.emplace_back(*IRHS);
3243 std::advance(IPriv, 1);
3244 std::advance(IRed, 1);
3245 std::advance(ILHS, 1);
3246 std::advance(IRHS, 1);
3247 }
3248 }
3249 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003250 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003251 LHSs, RHSs, Data);
3252 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3253 CGF.EmitVarDecl(*VD);
3254 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3255 /*Volatile=*/false, E->getType());
3256 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003257 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003258 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003259 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003260 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003261}
3262
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003263void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003264 CGM.getOpenMPRuntime().emitFlush(
3265 *this,
3266 [&S]() -> ArrayRef<const Expr *> {
3267 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3268 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3269 FlushClause->varlist_end());
3270 return llvm::None;
3271 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003272 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003273}
3274
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003275void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3276 const CodeGenLoopTy &CodeGenLoop,
3277 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003278 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003279 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3280 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003281 EmitVarDecl(*IVDecl);
3282
3283 // Emit the iterations count variable.
3284 // If it is not a variable, Sema decided to calculate iterations count on each
3285 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003286 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003287 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3288 // Emit calculation of the iterations count.
3289 EmitIgnoredExpr(S.getCalcLastIteration());
3290 }
3291
Alexey Bataevddf3db92018-04-13 17:31:06 +00003292 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003293
Carlo Bertolli962bb802017-01-03 18:24:42 +00003294 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003295 // Check pre-condition.
3296 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003297 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003298 // Skip the entire loop if we don't meet the precondition.
3299 // If the condition constant folds and can be elided, avoid emitting the
3300 // whole loop.
3301 bool CondConstant;
3302 llvm::BasicBlock *ContBlock = nullptr;
3303 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3304 if (!CondConstant)
3305 return;
3306 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003307 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003308 ContBlock = createBasicBlock("omp.precond.end");
3309 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3310 getProfileCount(&S));
3311 EmitBlock(ThenBlock);
3312 incrementProfileCounter(&S);
3313 }
3314
Alexey Bataev617db5f2017-12-04 15:38:33 +00003315 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003316 // Emit 'then' code.
3317 {
3318 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003319
3320 LValue LB = EmitOMPHelperVar(
3321 *this, cast<DeclRefExpr>(
3322 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3323 ? S.getCombinedLowerBoundVariable()
3324 : S.getLowerBoundVariable())));
3325 LValue UB = EmitOMPHelperVar(
3326 *this, cast<DeclRefExpr>(
3327 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3328 ? S.getCombinedUpperBoundVariable()
3329 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003330 LValue ST =
3331 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3332 LValue IL =
3333 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3334
3335 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003336 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003337 // Emit implicit barrier to synchronize threads and avoid data races
3338 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003339 // lastprivate variables.
3340 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003341 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003342 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003343 }
3344 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003345 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003346 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3347 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003348 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003349 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003350 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003351 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003352 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3353 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003354
3355 // Detect the distribute schedule kind and chunk.
3356 llvm::Value *Chunk = nullptr;
3357 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003358 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003359 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003360 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003361 Chunk = EmitScalarExpr(Ch);
3362 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003363 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003364 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003365 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003366 } else {
3367 // Default behaviour for dist_schedule clause.
3368 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3369 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003370 }
3371 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3372 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3373
3374 // OpenMP [2.10.8, distribute Construct, Description]
3375 // If dist_schedule is specified, kind must be static. If specified,
3376 // iterations are divided into chunks of size chunk_size, chunks are
3377 // assigned to the teams of the league in a round-robin fashion in the
3378 // order of the team number. When no chunk_size is specified, the
3379 // iteration space is divided into chunks that are approximately equal
3380 // in size, and at most one chunk is distributed to each team of the
3381 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003382 bool StaticChunked = RT.isStaticChunked(
3383 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3384 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003386 /* Chunked */ Chunk != nullptr) ||
3387 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003388 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3389 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003390 CGOpenMPRuntime::StaticRTInput StaticInit(
3391 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003392 LB.getAddress(), UB.getAddress(), ST.getAddress(),
3393 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003394 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003395 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003396 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003397 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3398 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003399 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3400 ? S.getCombinedEnsureUpperBound()
3401 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003402 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003403 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3404 ? S.getCombinedInit()
3405 : S.getInit());
3406
Alexey Bataevddf3db92018-04-13 17:31:06 +00003407 const Expr *Cond =
3408 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3409 ? S.getCombinedCond()
3410 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003411
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003412 if (StaticChunked)
3413 Cond = S.getCombinedDistCond();
3414
3415 // For static unchunked schedules generate:
3416 //
3417 // 1. For distribute alone, codegen
3418 // while (idx <= UB) {
3419 // BODY;
3420 // ++idx;
3421 // }
3422 //
3423 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3424 // while (idx <= UB) {
3425 // <CodeGen rest of pragma>(LB, UB);
3426 // idx += ST;
3427 // }
3428 //
3429 // For static chunk one schedule generate:
3430 //
3431 // while (IV <= GlobalUB) {
3432 // <CodeGen rest of pragma>(LB, UB);
3433 // LB += ST;
3434 // UB += ST;
3435 // UB = min(UB, GlobalUB);
3436 // IV = LB;
3437 // }
3438 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003439 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3440 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3441 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003442 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003443 [&S, StaticChunked](CodeGenFunction &CGF) {
3444 if (StaticChunked) {
3445 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3446 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3447 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3448 CGF.EmitIgnoredExpr(S.getCombinedInit());
3449 }
3450 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003451 EmitBlock(LoopExit.getBlock());
3452 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003453 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003454 } else {
3455 // Emit the outer loop, which requests its work chunk [LB..UB] from
3456 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003457 const OMPLoopArguments LoopArguments = {
3458 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3459 Chunk};
3460 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3461 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003462 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003463 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003464 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003465 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003466 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003467 });
3468 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003469 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3470 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3471 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003472 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003473 // Emit post-update of the reduction variables if IsLastIter != 0.
3474 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003475 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003476 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003477 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003478 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003479 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003480 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003481 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003482 EmitOMPLastprivateClauseFinal(
3483 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003484 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003485 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003486 }
3487
3488 // We're now done with the loop, so jump to the continuation block.
3489 if (ContBlock) {
3490 EmitBranch(ContBlock);
3491 EmitBlock(ContBlock, true);
3492 }
3493 }
3494}
3495
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003496void CodeGenFunction::EmitOMPDistributeDirective(
3497 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003498 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003499 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003500 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003501 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003502 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003503}
3504
Alexey Bataev5f600d62015-09-29 03:48:57 +00003505static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3506 const CapturedStmt *S) {
3507 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3508 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3509 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003510 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003511 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003512 return Fn;
3513}
3514
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003515void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003516 if (S.hasClausesOfKind<OMPDependClause>()) {
3517 assert(!S.getAssociatedStmt() &&
3518 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003519 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3520 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003521 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003522 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003523 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003524 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3525 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003526 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003527 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003528 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3529 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003530 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003531 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003532 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003533 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003534 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003535 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003536 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003537 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003538 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003539 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003540}
3541
Alexey Bataevb57056f2015-01-22 06:17:56 +00003542static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003543 QualType SrcType, QualType DestType,
3544 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003545 assert(CGF.hasScalarEvaluationKind(DestType) &&
3546 "DestType must have scalar evaluation kind.");
3547 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003548 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3549 DestType, Loc)
3550 : CGF.EmitComplexToScalarConversion(
3551 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003552}
3553
3554static CodeGenFunction::ComplexPairTy
3555convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003556 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003557 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3558 "DestType must have complex evaluation kind.");
3559 CodeGenFunction::ComplexPairTy ComplexVal;
3560 if (Val.isScalar()) {
3561 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003562 QualType DestElementType =
3563 DestType->castAs<ComplexType>()->getElementType();
3564 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3565 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003566 ComplexVal = CodeGenFunction::ComplexPairTy(
3567 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3568 } else {
3569 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003570 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3571 QualType DestElementType =
3572 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003573 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003574 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003575 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003576 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003577 }
3578 return ComplexVal;
3579}
3580
Alexey Bataev5e018f92015-04-23 06:35:10 +00003581static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3582 LValue LVal, RValue RVal) {
3583 if (LVal.isGlobalReg()) {
3584 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3585 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003586 CGF.EmitAtomicStore(RVal, LVal,
3587 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3588 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003589 LVal.isVolatile(), /*IsInit=*/false);
3590 }
3591}
3592
Alexey Bataev8524d152016-01-21 12:35:58 +00003593void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3594 QualType RValTy, SourceLocation Loc) {
3595 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003596 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003597 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3598 *this, RVal, RValTy, LVal.getType(), Loc)),
3599 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003600 break;
3601 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003602 EmitStoreOfComplex(
3603 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003604 /*isInit=*/false);
3605 break;
3606 case TEK_Aggregate:
3607 llvm_unreachable("Must be a scalar or complex.");
3608 }
3609}
3610
Alexey Bataevddf3db92018-04-13 17:31:06 +00003611static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003612 const Expr *X, const Expr *V,
3613 SourceLocation Loc) {
3614 // v = x;
3615 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3616 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3617 LValue XLValue = CGF.EmitLValue(X);
3618 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003619 RValue Res = XLValue.isGlobalReg()
3620 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003621 : CGF.EmitAtomicLoad(
3622 XLValue, Loc,
3623 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3624 : llvm::AtomicOrdering::Monotonic,
3625 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003626 // OpenMP, 2.12.6, atomic Construct
3627 // Any atomic construct with a seq_cst clause forces the atomically
3628 // performed operation to include an implicit flush operation without a
3629 // list.
3630 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003631 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003632 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003633}
3634
Alexey Bataevddf3db92018-04-13 17:31:06 +00003635static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003636 const Expr *X, const Expr *E,
3637 SourceLocation Loc) {
3638 // x = expr;
3639 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003640 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003641 // OpenMP, 2.12.6, atomic Construct
3642 // Any atomic construct with a seq_cst clause forces the atomically
3643 // performed operation to include an implicit flush operation without a
3644 // list.
3645 if (IsSeqCst)
3646 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3647}
3648
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003649static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3650 RValue Update,
3651 BinaryOperatorKind BO,
3652 llvm::AtomicOrdering AO,
3653 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003654 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003655 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003656 // expression is simple and atomic is allowed for the given type for the
3657 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003658 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003659 !Update.getScalarVal()->getType()->isIntegerTy() ||
3660 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3661 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003662 X.getAddress().getElementType())) ||
3663 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003664 !Context.getTargetInfo().hasBuiltinAtomic(
3665 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003666 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003667
3668 llvm::AtomicRMWInst::BinOp RMWOp;
3669 switch (BO) {
3670 case BO_Add:
3671 RMWOp = llvm::AtomicRMWInst::Add;
3672 break;
3673 case BO_Sub:
3674 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003675 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003676 RMWOp = llvm::AtomicRMWInst::Sub;
3677 break;
3678 case BO_And:
3679 RMWOp = llvm::AtomicRMWInst::And;
3680 break;
3681 case BO_Or:
3682 RMWOp = llvm::AtomicRMWInst::Or;
3683 break;
3684 case BO_Xor:
3685 RMWOp = llvm::AtomicRMWInst::Xor;
3686 break;
3687 case BO_LT:
3688 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3689 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3690 : llvm::AtomicRMWInst::Max)
3691 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3692 : llvm::AtomicRMWInst::UMax);
3693 break;
3694 case BO_GT:
3695 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3696 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3697 : llvm::AtomicRMWInst::Min)
3698 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3699 : llvm::AtomicRMWInst::UMin);
3700 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003701 case BO_Assign:
3702 RMWOp = llvm::AtomicRMWInst::Xchg;
3703 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003704 case BO_Mul:
3705 case BO_Div:
3706 case BO_Rem:
3707 case BO_Shl:
3708 case BO_Shr:
3709 case BO_LAnd:
3710 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003711 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003712 case BO_PtrMemD:
3713 case BO_PtrMemI:
3714 case BO_LE:
3715 case BO_GE:
3716 case BO_EQ:
3717 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003718 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003719 case BO_AddAssign:
3720 case BO_SubAssign:
3721 case BO_AndAssign:
3722 case BO_OrAssign:
3723 case BO_XorAssign:
3724 case BO_MulAssign:
3725 case BO_DivAssign:
3726 case BO_RemAssign:
3727 case BO_ShlAssign:
3728 case BO_ShrAssign:
3729 case BO_Comma:
3730 llvm_unreachable("Unsupported atomic update operation");
3731 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003732 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003733 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3734 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003735 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003736 X.getType()->hasSignedIntegerRepresentation());
3737 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003738 llvm::Value *Res =
3739 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003740 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003741}
3742
Alexey Bataev5e018f92015-04-23 06:35:10 +00003743std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003744 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3745 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003746 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003747 // Update expressions are allowed to have the following forms:
3748 // x binop= expr; -> xrval + expr;
3749 // x++, ++x -> xrval + 1;
3750 // x--, --x -> xrval - 1;
3751 // x = x binop expr; -> xrval binop expr
3752 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003753 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3754 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003755 if (X.isGlobalReg()) {
3756 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3757 // 'xrval'.
3758 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3759 } else {
3760 // Perform compare-and-swap procedure.
3761 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003762 }
3763 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003764 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003765}
3766
Alexey Bataevddf3db92018-04-13 17:31:06 +00003767static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003768 const Expr *X, const Expr *E,
3769 const Expr *UE, bool IsXLHSInRHSPart,
3770 SourceLocation Loc) {
3771 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3772 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003773 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003774 // Update expressions are allowed to have the following forms:
3775 // x binop= expr; -> xrval + expr;
3776 // x++, ++x -> xrval + 1;
3777 // x--, --x -> xrval - 1;
3778 // x = x binop expr; -> xrval binop expr
3779 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003780 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003781 LValue XLValue = CGF.EmitLValue(X);
3782 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003783 llvm::AtomicOrdering AO = IsSeqCst
3784 ? llvm::AtomicOrdering::SequentiallyConsistent
3785 : llvm::AtomicOrdering::Monotonic;
3786 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3787 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3788 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3789 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3790 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3791 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3792 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3793 return CGF.EmitAnyExpr(UE);
3794 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003795 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3796 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3797 // OpenMP, 2.12.6, atomic Construct
3798 // Any atomic construct with a seq_cst clause forces the atomically
3799 // performed operation to include an implicit flush operation without a
3800 // list.
3801 if (IsSeqCst)
3802 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3803}
3804
3805static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003806 QualType SourceType, QualType ResType,
3807 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003808 switch (CGF.getEvaluationKind(ResType)) {
3809 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003810 return RValue::get(
3811 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003812 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003813 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003814 return RValue::getComplex(Res.first, Res.second);
3815 }
3816 case TEK_Aggregate:
3817 break;
3818 }
3819 llvm_unreachable("Must be a scalar or complex.");
3820}
3821
Alexey Bataevddf3db92018-04-13 17:31:06 +00003822static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003823 bool IsPostfixUpdate, const Expr *V,
3824 const Expr *X, const Expr *E,
3825 const Expr *UE, bool IsXLHSInRHSPart,
3826 SourceLocation Loc) {
3827 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3828 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3829 RValue NewVVal;
3830 LValue VLValue = CGF.EmitLValue(V);
3831 LValue XLValue = CGF.EmitLValue(X);
3832 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003833 llvm::AtomicOrdering AO = IsSeqCst
3834 ? llvm::AtomicOrdering::SequentiallyConsistent
3835 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003836 QualType NewVValType;
3837 if (UE) {
3838 // 'x' is updated with some additional value.
3839 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3840 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003841 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00003842 // Update expressions are allowed to have the following forms:
3843 // x binop= expr; -> xrval + expr;
3844 // x++, ++x -> xrval + 1;
3845 // x--, --x -> xrval - 1;
3846 // x = x binop expr; -> xrval binop expr
3847 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003848 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3849 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3850 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003851 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003852 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003853 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003854 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003855 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3856 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3857 RValue Res = CGF.EmitAnyExpr(UE);
3858 NewVVal = IsPostfixUpdate ? XRValue : Res;
3859 return Res;
3860 };
3861 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3862 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3863 if (Res.first) {
3864 // 'atomicrmw' instruction was generated.
3865 if (IsPostfixUpdate) {
3866 // Use old value from 'atomicrmw'.
3867 NewVVal = Res.second;
3868 } else {
3869 // 'atomicrmw' does not provide new value, so evaluate it using old
3870 // value of 'x'.
3871 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3872 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3873 NewVVal = CGF.EmitAnyExpr(UE);
3874 }
3875 }
3876 } else {
3877 // 'x' is simply rewritten with some 'expr'.
3878 NewVValType = X->getType().getNonReferenceType();
3879 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003880 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003881 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003882 NewVVal = XRValue;
3883 return ExprRValue;
3884 };
3885 // Try to perform atomicrmw xchg, otherwise simple exchange.
3886 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3887 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3888 Loc, Gen);
3889 if (Res.first) {
3890 // 'atomicrmw' instruction was generated.
3891 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3892 }
3893 }
3894 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003895 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003896 // OpenMP, 2.12.6, atomic Construct
3897 // Any atomic construct with a seq_cst clause forces the atomically
3898 // performed operation to include an implicit flush operation without a
3899 // list.
3900 if (IsSeqCst)
3901 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3902}
3903
Alexey Bataevddf3db92018-04-13 17:31:06 +00003904static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003905 bool IsSeqCst, bool IsPostfixUpdate,
3906 const Expr *X, const Expr *V, const Expr *E,
3907 const Expr *UE, bool IsXLHSInRHSPart,
3908 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003909 switch (Kind) {
3910 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003911 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003912 break;
3913 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003914 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00003915 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003916 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003917 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003918 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003919 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003920 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003921 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003922 IsXLHSInRHSPart, Loc);
3923 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003924 case OMPC_if:
3925 case OMPC_final:
3926 case OMPC_num_threads:
3927 case OMPC_private:
3928 case OMPC_firstprivate:
3929 case OMPC_lastprivate:
3930 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003931 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003932 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003933 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003934 case OMPC_simdlen:
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 };
4082 CGM.getOpenMPRuntime().emitTargetNumIterationsCall(CGF, S, Device,
4083 SizeEmitter);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004084 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004085}
4086
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004087static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4088 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004089 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004090 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4091 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4092 CGF.EmitOMPPrivateClause(S, PrivateScope);
4093 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004094 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4095 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004096
Alexey Bataev475a7442018-01-12 19:39:11 +00004097 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004098}
4099
4100void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4101 StringRef ParentName,
4102 const OMPTargetDirective &S) {
4103 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4104 emitTargetRegion(CGF, S, Action);
4105 };
4106 llvm::Function *Fn;
4107 llvm::Constant *Addr;
4108 // Emit target region as a standalone region.
4109 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4110 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4111 assert(Fn && Addr && "Target device function emission failed.");
4112}
4113
4114void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4115 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4116 emitTargetRegion(CGF, S, Action);
4117 };
4118 emitCommonOMPTargetDirective(*this, S, CodeGen);
4119}
4120
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004121static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4122 const OMPExecutableDirective &S,
4123 OpenMPDirectiveKind InnermostKind,
4124 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004125 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004126 llvm::Value *OutlinedFn =
4127 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4128 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004129
Alexey Bataevddf3db92018-04-13 17:31:06 +00004130 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4131 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004132 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004133 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4134 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004135
Carlo Bertollic6872252016-04-04 15:55:02 +00004136 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004137 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004138 }
4139
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004140 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004141 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4142 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004143 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004144 CapturedVars);
4145}
4146
4147void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004148 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004149 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004150 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004151 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004152 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4153 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004154 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004155 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004156 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004157 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004158 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004159 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004160 emitPostUpdateForReductionClause(*this, S,
4161 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004162}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004163
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004164static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4165 const OMPTargetTeamsDirective &S) {
4166 auto *CS = S.getCapturedStmt(OMPD_teams);
4167 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004168 // Emit teams region as a standalone region.
4169 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004170 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004171 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4172 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4173 CGF.EmitOMPPrivateClause(S, PrivateScope);
4174 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4175 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004176 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4177 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004178 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004179 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004180 };
4181 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004182 emitPostUpdateForReductionClause(CGF, S,
4183 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004184}
4185
4186void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4187 CodeGenModule &CGM, StringRef ParentName,
4188 const OMPTargetTeamsDirective &S) {
4189 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4190 emitTargetTeamsRegion(CGF, Action, S);
4191 };
4192 llvm::Function *Fn;
4193 llvm::Constant *Addr;
4194 // Emit target region as a standalone region.
4195 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4196 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4197 assert(Fn && Addr && "Target device function emission failed.");
4198}
4199
4200void CodeGenFunction::EmitOMPTargetTeamsDirective(
4201 const OMPTargetTeamsDirective &S) {
4202 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4203 emitTargetTeamsRegion(CGF, Action, S);
4204 };
4205 emitCommonOMPTargetDirective(*this, S, CodeGen);
4206}
4207
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004208static void
4209emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4210 const OMPTargetTeamsDistributeDirective &S) {
4211 Action.Enter(CGF);
4212 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4213 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4214 };
4215
4216 // Emit teams region as a standalone region.
4217 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004218 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004219 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004220 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4221 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4222 (void)PrivateScope.Privatize();
4223 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4224 CodeGenDistribute);
4225 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4226 };
4227 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4228 emitPostUpdateForReductionClause(CGF, S,
4229 [](CodeGenFunction &) { return nullptr; });
4230}
4231
4232void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4233 CodeGenModule &CGM, StringRef ParentName,
4234 const OMPTargetTeamsDistributeDirective &S) {
4235 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4236 emitTargetTeamsDistributeRegion(CGF, Action, S);
4237 };
4238 llvm::Function *Fn;
4239 llvm::Constant *Addr;
4240 // Emit target region as a standalone region.
4241 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4242 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4243 assert(Fn && Addr && "Target device function emission failed.");
4244}
4245
4246void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4247 const OMPTargetTeamsDistributeDirective &S) {
4248 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4249 emitTargetTeamsDistributeRegion(CGF, Action, S);
4250 };
4251 emitCommonOMPTargetDirective(*this, S, CodeGen);
4252}
4253
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004254static void emitTargetTeamsDistributeSimdRegion(
4255 CodeGenFunction &CGF, PrePostActionTy &Action,
4256 const OMPTargetTeamsDistributeSimdDirective &S) {
4257 Action.Enter(CGF);
4258 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4259 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4260 };
4261
4262 // Emit teams region as a standalone region.
4263 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004264 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004265 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004266 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4267 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4268 (void)PrivateScope.Privatize();
4269 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4270 CodeGenDistribute);
4271 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4272 };
4273 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4274 emitPostUpdateForReductionClause(CGF, S,
4275 [](CodeGenFunction &) { return nullptr; });
4276}
4277
4278void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4279 CodeGenModule &CGM, StringRef ParentName,
4280 const OMPTargetTeamsDistributeSimdDirective &S) {
4281 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4282 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4283 };
4284 llvm::Function *Fn;
4285 llvm::Constant *Addr;
4286 // Emit target region as a standalone region.
4287 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4288 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4289 assert(Fn && Addr && "Target device function emission failed.");
4290}
4291
4292void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4293 const OMPTargetTeamsDistributeSimdDirective &S) {
4294 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4295 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4296 };
4297 emitCommonOMPTargetDirective(*this, S, CodeGen);
4298}
4299
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004300void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4301 const OMPTeamsDistributeDirective &S) {
4302
4303 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4304 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4305 };
4306
4307 // Emit teams region as a standalone region.
4308 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004309 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004310 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004311 OMPPrivateScope PrivateScope(CGF);
4312 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4313 (void)PrivateScope.Privatize();
4314 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4315 CodeGenDistribute);
4316 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4317 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004318 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004319 emitPostUpdateForReductionClause(*this, S,
4320 [](CodeGenFunction &) { return nullptr; });
4321}
4322
Alexey Bataev999277a2017-12-06 14:31:09 +00004323void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4324 const OMPTeamsDistributeSimdDirective &S) {
4325 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4326 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4327 };
4328
4329 // Emit teams region as a standalone region.
4330 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004331 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004332 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004333 OMPPrivateScope PrivateScope(CGF);
4334 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4335 (void)PrivateScope.Privatize();
4336 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4337 CodeGenDistribute);
4338 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4339 };
4340 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4341 emitPostUpdateForReductionClause(*this, S,
4342 [](CodeGenFunction &) { return nullptr; });
4343}
4344
Carlo Bertolli62fae152017-11-20 20:46:39 +00004345void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4346 const OMPTeamsDistributeParallelForDirective &S) {
4347 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4348 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4349 S.getDistInc());
4350 };
4351
4352 // Emit teams region as a standalone region.
4353 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004354 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004355 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004356 OMPPrivateScope PrivateScope(CGF);
4357 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4358 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004359 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4360 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004361 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4362 };
4363 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4364 emitPostUpdateForReductionClause(*this, S,
4365 [](CodeGenFunction &) { return nullptr; });
4366}
4367
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004368void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4369 const OMPTeamsDistributeParallelForSimdDirective &S) {
4370 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4371 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4372 S.getDistInc());
4373 };
4374
4375 // Emit teams region as a standalone region.
4376 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004377 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004378 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004379 OMPPrivateScope PrivateScope(CGF);
4380 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4381 (void)PrivateScope.Privatize();
4382 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4383 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4384 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4385 };
4386 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4387 emitPostUpdateForReductionClause(*this, S,
4388 [](CodeGenFunction &) { return nullptr; });
4389}
4390
Carlo Bertolli52978c32018-01-03 21:12:44 +00004391static void emitTargetTeamsDistributeParallelForRegion(
4392 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4393 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004394 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004395 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4396 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4397 S.getDistInc());
4398 };
4399
4400 // Emit teams region as a standalone region.
4401 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004402 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004403 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004404 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4405 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4406 (void)PrivateScope.Privatize();
4407 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4408 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4409 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4410 };
4411
4412 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4413 CodeGenTeams);
4414 emitPostUpdateForReductionClause(CGF, S,
4415 [](CodeGenFunction &) { return nullptr; });
4416}
4417
4418void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4419 CodeGenModule &CGM, StringRef ParentName,
4420 const OMPTargetTeamsDistributeParallelForDirective &S) {
4421 // Emit SPMD target teams distribute parallel for region as a standalone
4422 // region.
4423 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4424 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4425 };
4426 llvm::Function *Fn;
4427 llvm::Constant *Addr;
4428 // Emit target region as a standalone region.
4429 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4430 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4431 assert(Fn && Addr && "Target device function emission failed.");
4432}
4433
4434void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4435 const OMPTargetTeamsDistributeParallelForDirective &S) {
4436 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4437 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4438 };
4439 emitCommonOMPTargetDirective(*this, S, CodeGen);
4440}
4441
Alexey Bataev647dd842018-01-15 20:59:40 +00004442static void emitTargetTeamsDistributeParallelForSimdRegion(
4443 CodeGenFunction &CGF,
4444 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4445 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004446 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004447 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4448 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4449 S.getDistInc());
4450 };
4451
4452 // Emit teams region as a standalone region.
4453 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004454 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004455 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004456 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4457 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4458 (void)PrivateScope.Privatize();
4459 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4460 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4461 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4462 };
4463
4464 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4465 CodeGenTeams);
4466 emitPostUpdateForReductionClause(CGF, S,
4467 [](CodeGenFunction &) { return nullptr; });
4468}
4469
4470void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4471 CodeGenModule &CGM, StringRef ParentName,
4472 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4473 // Emit SPMD target teams distribute parallel for simd region as a standalone
4474 // region.
4475 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4476 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4477 };
4478 llvm::Function *Fn;
4479 llvm::Constant *Addr;
4480 // Emit target region as a standalone region.
4481 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4482 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4483 assert(Fn && Addr && "Target device function emission failed.");
4484}
4485
4486void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4487 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4488 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4489 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4490 };
4491 emitCommonOMPTargetDirective(*this, S, CodeGen);
4492}
4493
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004494void CodeGenFunction::EmitOMPCancellationPointDirective(
4495 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004496 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004497 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004498}
4499
Alexey Bataev80909872015-07-02 11:25:17 +00004500void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004501 const Expr *IfCond = nullptr;
4502 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4503 if (C->getNameModifier() == OMPD_unknown ||
4504 C->getNameModifier() == OMPD_cancel) {
4505 IfCond = C->getCondition();
4506 break;
4507 }
4508 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004509 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004510 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004511}
4512
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004513CodeGenFunction::JumpDest
4514CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004515 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4516 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004517 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004518 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004519 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4520 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004521 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004522 Kind == OMPD_teams_distribute_parallel_for ||
4523 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004524 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004525}
Michael Wong65f367f2015-07-21 13:44:28 +00004526
Samuel Antaocc10b852016-07-28 14:23:26 +00004527void CodeGenFunction::EmitOMPUseDevicePtrClause(
4528 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4529 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4530 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4531 auto OrigVarIt = C.varlist_begin();
4532 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004533 for (const Expr *PvtVarIt : C.private_copies()) {
4534 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4535 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4536 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004537
4538 // In order to identify the right initializer we need to match the
4539 // declaration used by the mapping logic. In some cases we may get
4540 // OMPCapturedExprDecl that refers to the original declaration.
4541 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004542 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004543 // OMPCapturedExprDecl are used to privative fields of the current
4544 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004545 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004546 assert(isa<CXXThisExpr>(ME->getBase()) &&
4547 "Base should be the current struct!");
4548 MatchingVD = ME->getMemberDecl();
4549 }
4550
4551 // If we don't have information about the current list item, move on to
4552 // the next one.
4553 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4554 if (InitAddrIt == CaptureDeviceAddrMap.end())
4555 continue;
4556
Alexey Bataevddf3db92018-04-13 17:31:06 +00004557 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4558 InitAddrIt, InitVD,
4559 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004560 // Initialize the temporary initialization variable with the address we
4561 // get from the runtime library. We have to cast the source address
4562 // because it is always a void *. References are materialized in the
4563 // privatization scope, so the initialization here disregards the fact
4564 // the original variable is a reference.
4565 QualType AddrQTy =
4566 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4567 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4568 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4569 setAddrOfLocalVar(InitVD, InitAddr);
4570
4571 // Emit private declaration, it will be initialized by the value we
4572 // declaration we just added to the local declarations map.
4573 EmitDecl(*PvtVD);
4574
4575 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004576 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004577 LocalDeclMap.erase(InitVD);
4578
4579 // Return the address of the private variable.
4580 return GetAddrOfLocalVar(PvtVD);
4581 });
4582 assert(IsRegistered && "firstprivate var already registered as private");
4583 // Silence the warning about unused variable.
4584 (void)IsRegistered;
4585
4586 ++OrigVarIt;
4587 ++InitIt;
4588 }
4589}
4590
Michael Wong65f367f2015-07-21 13:44:28 +00004591// Generate the instructions for '#pragma omp target data' directive.
4592void CodeGenFunction::EmitOMPTargetDataDirective(
4593 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004594 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4595
4596 // Create a pre/post action to signal the privatization of the device pointer.
4597 // This action can be replaced by the OpenMP runtime code generation to
4598 // deactivate privatization.
4599 bool PrivatizeDevicePointers = false;
4600 class DevicePointerPrivActionTy : public PrePostActionTy {
4601 bool &PrivatizeDevicePointers;
4602
4603 public:
4604 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4605 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4606 void Enter(CodeGenFunction &CGF) override {
4607 PrivatizeDevicePointers = true;
4608 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004609 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004610 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4611
4612 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004613 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004614 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004615 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004616 };
4617
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004618 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004619 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4620 &InnermostCodeGen](CodeGenFunction &CGF,
4621 PrePostActionTy &Action) {
4622 RegionCodeGenTy RCG(InnermostCodeGen);
4623 PrivatizeDevicePointers = false;
4624
4625 // Call the pre-action to change the status of PrivatizeDevicePointers if
4626 // needed.
4627 Action.Enter(CGF);
4628
4629 if (PrivatizeDevicePointers) {
4630 OMPPrivateScope PrivateScope(CGF);
4631 // Emit all instances of the use_device_ptr clause.
4632 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4633 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4634 Info.CaptureDeviceAddrMap);
4635 (void)PrivateScope.Privatize();
4636 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004637 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004638 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004639 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004640 };
4641
4642 // Forward the provided action to the privatization codegen.
4643 RegionCodeGenTy PrivRCG(PrivCodeGen);
4644 PrivRCG.setAction(Action);
4645
4646 // Notwithstanding the body of the region is emitted as inlined directive,
4647 // we don't use an inline scope as changes in the references inside the
4648 // region are expected to be visible outside, so we do not privative them.
4649 OMPLexicalScope Scope(CGF, S);
4650 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4651 PrivRCG);
4652 };
4653
4654 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004655
4656 // If we don't have target devices, don't bother emitting the data mapping
4657 // code.
4658 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004659 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004660 return;
4661 }
4662
4663 // Check if we have any if clause associated with the directive.
4664 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004665 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004666 IfCond = C->getCondition();
4667
4668 // Check if we have any device clause associated with the directive.
4669 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004670 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004671 Device = C->getDevice();
4672
Samuel Antaocc10b852016-07-28 14:23:26 +00004673 // Set the action to signal privatization of device pointers.
4674 RCG.setAction(PrivAction);
4675
4676 // Emit region code.
4677 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4678 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004679}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004680
Samuel Antaodf67fc42016-01-19 19:15:56 +00004681void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4682 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004683 // If we don't have target devices, don't bother emitting the data mapping
4684 // code.
4685 if (CGM.getLangOpts().OMPTargetTriples.empty())
4686 return;
4687
4688 // Check if we have any if clause associated with the directive.
4689 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004690 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004691 IfCond = C->getCondition();
4692
4693 // Check if we have any device clause associated with the directive.
4694 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004695 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004696 Device = C->getDevice();
4697
Alexey Bataev475a7442018-01-12 19:39:11 +00004698 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004699 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004700}
4701
Samuel Antao72590762016-01-19 20:04:50 +00004702void CodeGenFunction::EmitOMPTargetExitDataDirective(
4703 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004704 // If we don't have target devices, don't bother emitting the data mapping
4705 // code.
4706 if (CGM.getLangOpts().OMPTargetTriples.empty())
4707 return;
4708
4709 // Check if we have any if clause associated with the directive.
4710 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004711 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004712 IfCond = C->getCondition();
4713
4714 // Check if we have any device clause associated with the directive.
4715 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004716 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004717 Device = C->getDevice();
4718
Alexey Bataev475a7442018-01-12 19:39:11 +00004719 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004720 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004721}
4722
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004723static void emitTargetParallelRegion(CodeGenFunction &CGF,
4724 const OMPTargetParallelDirective &S,
4725 PrePostActionTy &Action) {
4726 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004727 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004728 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004729 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004730 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004731 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4732 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4733 CGF.EmitOMPPrivateClause(S, PrivateScope);
4734 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4735 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004736 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4737 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004738 // TODO: Add support for clauses.
4739 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004740 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004741 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004742 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4743 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004744 emitPostUpdateForReductionClause(CGF, S,
4745 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004746}
4747
4748void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4749 CodeGenModule &CGM, StringRef ParentName,
4750 const OMPTargetParallelDirective &S) {
4751 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4752 emitTargetParallelRegion(CGF, S, Action);
4753 };
4754 llvm::Function *Fn;
4755 llvm::Constant *Addr;
4756 // Emit target region as a standalone region.
4757 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4758 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4759 assert(Fn && Addr && "Target device function emission failed.");
4760}
4761
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004762void CodeGenFunction::EmitOMPTargetParallelDirective(
4763 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004764 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4765 emitTargetParallelRegion(CGF, S, Action);
4766 };
4767 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004768}
4769
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004770static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4771 const OMPTargetParallelForDirective &S,
4772 PrePostActionTy &Action) {
4773 Action.Enter(CGF);
4774 // Emit directive as a combined directive that consists of two implicit
4775 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004776 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4777 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004778 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4779 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004780 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4781 emitDispatchForLoopBounds);
4782 };
4783 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4784 emitEmptyBoundParameters);
4785}
4786
4787void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4788 CodeGenModule &CGM, StringRef ParentName,
4789 const OMPTargetParallelForDirective &S) {
4790 // Emit SPMD target parallel for region as a standalone region.
4791 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4792 emitTargetParallelForRegion(CGF, S, Action);
4793 };
4794 llvm::Function *Fn;
4795 llvm::Constant *Addr;
4796 // Emit target region as a standalone region.
4797 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4798 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4799 assert(Fn && Addr && "Target device function emission failed.");
4800}
4801
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004802void CodeGenFunction::EmitOMPTargetParallelForDirective(
4803 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004804 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4805 emitTargetParallelForRegion(CGF, S, Action);
4806 };
4807 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004808}
4809
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004810static void
4811emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4812 const OMPTargetParallelForSimdDirective &S,
4813 PrePostActionTy &Action) {
4814 Action.Enter(CGF);
4815 // Emit directive as a combined directive that consists of two implicit
4816 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004817 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4818 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004819 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4820 emitDispatchForLoopBounds);
4821 };
4822 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4823 emitEmptyBoundParameters);
4824}
4825
4826void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4827 CodeGenModule &CGM, StringRef ParentName,
4828 const OMPTargetParallelForSimdDirective &S) {
4829 // Emit SPMD target parallel for region as a standalone region.
4830 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4831 emitTargetParallelForSimdRegion(CGF, S, Action);
4832 };
4833 llvm::Function *Fn;
4834 llvm::Constant *Addr;
4835 // Emit target region as a standalone region.
4836 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4837 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4838 assert(Fn && Addr && "Target device function emission failed.");
4839}
4840
4841void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4842 const OMPTargetParallelForSimdDirective &S) {
4843 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4844 emitTargetParallelForSimdRegion(CGF, S, Action);
4845 };
4846 emitCommonOMPTargetDirective(*this, S, CodeGen);
4847}
4848
Alexey Bataev7292c292016-04-25 12:22:29 +00004849/// Emit a helper variable and return corresponding lvalue.
4850static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4851 const ImplicitParamDecl *PVD,
4852 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004853 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
4854 Privates.addPrivate(VDecl,
4855 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00004856}
4857
4858void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4859 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4860 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004861 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004862 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4863 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004864 const Expr *IfCond = nullptr;
4865 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4866 if (C->getNameModifier() == OMPD_unknown ||
4867 C->getNameModifier() == OMPD_taskloop) {
4868 IfCond = C->getCondition();
4869 break;
4870 }
4871 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004872
4873 OMPTaskDataTy Data;
4874 // Check if taskloop must be emitted without taskgroup.
4875 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004876 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004877 Data.Tied = true;
4878 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004879 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4880 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004881 Data.Schedule.setInt(/*IntVal=*/false);
4882 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004883 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4884 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004885 Data.Schedule.setInt(/*IntVal=*/true);
4886 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004887 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004888
4889 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4890 // if (PreCond) {
4891 // for (IV in 0..LastIteration) BODY;
4892 // <Final counter/linear vars updates>;
4893 // }
4894 //
4895
4896 // Emit: if (PreCond) - begin.
4897 // If the condition constant folds and can be elided, avoid emitting the
4898 // whole loop.
4899 bool CondConstant;
4900 llvm::BasicBlock *ContBlock = nullptr;
4901 OMPLoopScope PreInitScope(CGF, S);
4902 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4903 if (!CondConstant)
4904 return;
4905 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004906 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00004907 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4908 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4909 CGF.getProfileCount(&S));
4910 CGF.EmitBlock(ThenBlock);
4911 CGF.incrementProfileCounter(&S);
4912 }
4913
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004914 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4915 CGF.EmitOMPSimdInit(S);
4916
Alexey Bataev7292c292016-04-25 12:22:29 +00004917 OMPPrivateScope LoopScope(CGF);
4918 // Emit helper vars inits.
4919 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4920 auto *I = CS->getCapturedDecl()->param_begin();
4921 auto *LBP = std::next(I, LowerBound);
4922 auto *UBP = std::next(I, UpperBound);
4923 auto *STP = std::next(I, Stride);
4924 auto *LIP = std::next(I, LastIter);
4925 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4926 LoopScope);
4927 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4928 LoopScope);
4929 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4930 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4931 LoopScope);
4932 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004933 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004934 (void)LoopScope.Privatize();
4935 // Emit the loop iteration variable.
4936 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004937 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004938 CGF.EmitVarDecl(*IVDecl);
4939 CGF.EmitIgnoredExpr(S.getInit());
4940
4941 // Emit the iterations count variable.
4942 // If it is not a variable, Sema decided to calculate iterations count on
4943 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00004944 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004945 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4946 // Emit calculation of the iterations count.
4947 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4948 }
4949
4950 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4951 S.getInc(),
4952 [&S](CodeGenFunction &CGF) {
4953 CGF.EmitOMPLoopBody(S, JumpDest());
4954 CGF.EmitStopPoint(&S);
4955 },
4956 [](CodeGenFunction &) {});
4957 // Emit: if (PreCond) - end.
4958 if (ContBlock) {
4959 CGF.EmitBranch(ContBlock);
4960 CGF.EmitBlock(ContBlock, true);
4961 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004962 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4963 if (HasLastprivateClause) {
4964 CGF.EmitOMPLastprivateClauseFinal(
4965 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4966 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4967 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004968 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004969 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004970 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004971 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4972 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4973 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004974 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
4975 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004976 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004977 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004978 OutlinedFn, SharedsTy,
4979 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004980 };
4981 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4982 CodeGen);
4983 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004984 if (Data.Nogroup) {
4985 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4986 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004987 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4988 *this,
4989 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4990 PrePostActionTy &Action) {
4991 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004992 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4993 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004994 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004995 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00004996 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004997}
4998
Alexey Bataev49f6e782015-12-01 04:18:41 +00004999void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005000 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005001}
5002
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005003void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5004 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005005 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005006}
Samuel Antao686c70c2016-05-26 17:30:50 +00005007
5008// Generate the instructions for '#pragma omp target update' directive.
5009void CodeGenFunction::EmitOMPTargetUpdateDirective(
5010 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005011 // If we don't have target devices, don't bother emitting the data mapping
5012 // code.
5013 if (CGM.getLangOpts().OMPTargetTriples.empty())
5014 return;
5015
5016 // Check if we have any if clause associated with the directive.
5017 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005018 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005019 IfCond = C->getCondition();
5020
5021 // Check if we have any device clause associated with the directive.
5022 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005023 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005024 Device = C->getDevice();
5025
Alexey Bataev475a7442018-01-12 19:39:11 +00005026 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005027 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005028}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005029
5030void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5031 const OMPExecutableDirective &D) {
5032 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5033 return;
5034 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5035 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5036 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5037 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005038 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005039 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005040 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005041 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5042 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5043 LValue GlobLVal = CGF.EmitLValue(E);
5044 LoopGlobals.addPrivate(
5045 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
5046 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005047 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005048 // Emit only those that were not explicitly referenced in clauses.
5049 if (!CGF.LocalDeclMap.count(VD))
5050 CGF.EmitVarDecl(*VD);
5051 }
5052 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005053 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5054 if (!C->getNumForLoops())
5055 continue;
5056 for (unsigned I = LD->getCollapsedNumber(),
5057 E = C->getLoopNumIterations().size();
5058 I < E; ++I) {
5059 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005060 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005061 // Emit only those that were not explicitly referenced in clauses.
5062 if (!CGF.LocalDeclMap.count(VD))
5063 CGF.EmitVarDecl(*VD);
5064 }
5065 }
5066 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005067 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005068 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005069 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005070 }
5071 };
5072 OMPSimdLexicalScope Scope(*this, D);
5073 CGM.getOpenMPRuntime().emitInlinedDirective(
5074 *this,
5075 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5076 : D.getDirectiveKind(),
5077 CodeGen);
5078}
Alexey Bataevddf3db92018-04-13 17:31:06 +00005079