blob: 957bcc43db0c7e7580faa10c67a92046b375754e [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 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);
69 for (auto &C : CS->captures()) {
70 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
75 const_cast<VarDecl *>(VD),
76 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 Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 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);
George Burgess IV00f70bd2018-03-01 05:43:23 +0000130 if (auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
131 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()) {
159 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
160 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
161 for (const auto *I : PreInit->decls()) {
162 if (!I->hasAttr<OMPCaptureNoInitAttr>())
163 CGF.EmitVarDecl(cast<VarDecl>(*I));
164 else {
165 CodeGenFunction::AutoVarEmission Emission =
166 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
167 CGF.EmitAutoVarCleanups(Emission);
168 }
169 }
170 }
171 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
172 for (const Expr *E : UDP->varlists()) {
173 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
174 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
175 CGF.EmitVarDecl(*OED);
176 }
177 }
178 }
179 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
180 CGF.EmitOMPPrivateClause(S, InlinedShareds);
181 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
182 if (const Expr *E = TG->getReductionRef())
183 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
184 }
185 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
186 while (CS) {
187 for (auto &C : CS->captures()) {
188 if (C.capturesVariable() || C.capturesVariableByCopy()) {
189 auto *VD = C.getCapturedVar();
190 assert(VD == VD->getCanonicalDecl() &&
191 "Canonical decl must be captured.");
192 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
193 isCapturedVar(CGF, VD) ||
194 (CGF.CapturedStmtInfo &&
195 InlinedShareds.isGlobalVarCaptured(VD)),
196 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000197 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000198 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
199 return CGF.EmitLValue(&DRE).getAddress();
200 });
201 }
202 }
203 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
204 }
205 (void)InlinedShareds.Privatize();
206 }
207};
208
Alexey Bataev3392d762016-02-16 11:18:12 +0000209} // namespace
210
Alexey Bataevf8365372017-11-17 17:57:25 +0000211static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
212 const OMPExecutableDirective &S,
213 const RegionCodeGenTy &CodeGen);
214
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000215LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
216 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
217 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
218 OrigVD = OrigVD->getCanonicalDecl();
219 bool IsCaptured =
220 LambdaCaptureFields.lookup(OrigVD) ||
221 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
222 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
223 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
224 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
225 return EmitLValue(&DRE);
226 }
227 }
228 return EmitLValue(E);
229}
230
Alexey Bataev1189bd02016-01-26 12:20:39 +0000231llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
232 auto &C = getContext();
233 llvm::Value *Size = nullptr;
234 auto SizeInChars = C.getTypeSizeInChars(Ty);
235 if (SizeInChars.isZero()) {
236 // getTypeSizeInChars() returns 0 for a VLA.
237 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +0000238 auto VlaSize = getVLASize(VAT);
239 Ty = VlaSize.Type;
240 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
241 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000242 }
243 SizeInChars = C.getTypeSizeInChars(Ty);
244 if (SizeInChars.isZero())
245 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
246 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
247 } else
248 Size = CGM.getSize(SizeInChars);
249 return Size;
250}
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()) {
261 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000262 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000263 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000264 } else if (CurCap->capturesThis())
265 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +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()) {
272 auto &Ctx = getContext();
273 auto DstAddr = CreateMemTemp(
274 Ctx.getUIntPtrType(),
275 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
276 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
277
278 auto *SrcAddrVal = EmitScalarConversion(
279 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 Bataeva9b9cc02018-01-23 18:12:38 +0000304 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
305 Ctx.getUIntPtrType(),
306 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000307 auto TmpAddr =
308 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);
315 auto *RefVal = TmpAddr.getPointer();
316 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
317 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000318 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) {
325 if (T->isLValueReferenceType()) {
326 return C.getLValueReferenceType(
327 getCanonicalParamType(C, T.getNonReferenceType()),
328 /*SpelledAsLValue=*/false);
329 }
330 if (T->isPointerType())
331 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000332 if (auto *A = T->getAsArrayTypeUnsafe()) {
333 if (auto *VLA = dyn_cast<VariableArrayType>(A))
334 return getCanonicalParamType(C, VLA->getElementType());
335 else if (!A->isVariablyModifiedType())
336 return C.getCanonicalType(T);
337 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000338 return C.getCanonicalParamType(T);
339}
340
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000341namespace {
342 /// Contains required data for proper outlined function codegen.
343 struct FunctionOptions {
344 /// Captured statement for which the function is generated.
345 const CapturedStmt *S = nullptr;
346 /// true if cast to/from UIntPtr is required for variables captured by
347 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000348 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000349 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000351 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
355 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000356 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000357 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
358 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000359 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 };
361}
362
Alexey Bataeve754b182017-08-09 19:38:53 +0000363static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000364 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000365 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 &LocalAddrs,
367 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
368 &VLASizes,
369 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
370 const CapturedDecl *CD = FO.S->getCapturedDecl();
371 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000372 assert(CD->hasBody() && "missing CapturedDecl body");
373
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000375 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000378 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 Args.append(CD->param_begin(),
380 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000381 TargetArgs.append(
382 CD->param_begin(),
383 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000384 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000385 FunctionDecl *DebugFunctionDecl = nullptr;
386 if (!FO.UIntPtrCastRequired) {
387 FunctionProtoType::ExtProtoInfo EPI;
388 DebugFunctionDecl = FunctionDecl::Create(
389 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
390 SourceLocation(), DeclarationName(), Ctx.VoidTy,
391 Ctx.getTrivialTypeSourceInfo(
392 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
393 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
394 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 for (auto *FD : RD->fields()) {
396 QualType ArgType = FD->getType();
397 IdentifierInfo *II = nullptr;
398 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000399
400 // If this is a capture by copy and the type is not a pointer, the outlined
401 // function argument type should be uintptr and the value properly casted to
402 // uintptr. This is necessary given that the runtime library is only able to
403 // deal with pointers. We can pass in the same way the VLA type sizes to the
404 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000405 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000406 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 if (FO.UIntPtrCastRequired)
408 ArgType = Ctx.getUIntPtrType();
409 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000410
411 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000412 CapVar = I->getCapturedVar();
413 II = CapVar->getIdentifier();
414 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 else {
417 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000418 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000419 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000420 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000421 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000422 VarDecl *Arg;
423 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
424 Arg = ParmVarDecl::Create(
425 Ctx, DebugFunctionDecl,
426 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
427 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
428 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
429 } else {
430 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
431 II, ArgType, ImplicitParamDecl::Other);
432 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000433 Args.emplace_back(Arg);
434 // Do not cast arguments if we emit function with non-original types.
435 TargetArgs.emplace_back(
436 FO.UIntPtrCastRequired
437 ? Arg
438 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000439 ++I;
440 }
441 Args.append(
442 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
443 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000444 TargetArgs.append(
445 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
446 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000447
448 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000451 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
452
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000453 llvm::Function *F =
454 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
455 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000456 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
457 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000458 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000459
460 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000461 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
462 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000463 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000464 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000466 // Do not map arguments if we emit function with non-original types.
467 Address LocalAddr(Address::invalid());
468 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
469 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
470 TargetArgs[Cnt]);
471 } else {
472 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
473 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000474 // If we are capturing a pointer by copy we don't need to do anything, just
475 // use the value that we get from the arguments.
476 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000477 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000478 // If the variable is a reference we need to materialize it here.
479 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000480 Address RefAddr = CGF.CreateMemTemp(
481 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
482 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
483 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000484 LocalAddr = RefAddr;
485 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000486 if (!FO.RegisterCastedArgsOnly)
487 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000488 ++Cnt;
489 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000490 continue;
491 }
492
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000493 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
494 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000495 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000496 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000497 ArgLVal = CGF.MakeAddrLValue(
498 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
499 Args[Cnt]->getName(), ArgLVal),
500 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 }
Alexey Bataev1e491372018-01-23 18:44:14 +0000502 auto *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000503 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 } else if (I->capturesVariable()) {
506 auto *Var = I->getCapturedVar();
507 QualType VarTy = Var->getType();
508 Address ArgAddr = ArgLVal.getAddress();
509 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000510 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000511 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000512 } else if (!VarTy->isVariablyModifiedType() || !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.");
526 auto *Var = I->getCapturedVar();
527 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);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000588 Args.clear();
589 LocalAddrs.clear();
590 VLASizes.clear();
591 llvm::Function *WrapperF =
592 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000593 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000594 llvm::SmallVector<llvm::Value *, 4> CallArgs;
595 for (const auto *Arg : Args) {
596 llvm::Value *CallArg;
597 auto I = LocalAddrs.find(Arg);
598 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000599 LValue LV = WrapperCGF.MakeAddrLValue(
600 I->second.second,
601 I->second.first ? I->second.first->getType() : Arg->getType(),
602 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000603 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000604 } else {
605 auto EI = VLASizes.find(Arg);
606 if (EI != VLASizes.end())
607 CallArg = EI->second.second;
608 else {
609 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000610 Arg->getType(),
611 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000612 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000613 }
614 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000615 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000616 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
618 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000619 WrapperCGF.FinishFunction();
620 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000621}
622
Alexey Bataev9959db52014-05-06 10:08:46 +0000623//===----------------------------------------------------------------------===//
624// OpenMP Directive Emission
625//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000626void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000627 Address DestAddr, Address SrcAddr, QualType OriginalType,
628 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629 // Perform element-by-element initialization.
630 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000631
632 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000633 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000634 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
635 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
636
637 auto SrcBegin = SrcAddr.getPointer();
638 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000639 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
641 // The basic structure here is a while-do loop.
642 auto BodyBB = createBasicBlock("omp.arraycpy.body");
643 auto DoneBB = createBasicBlock("omp.arraycpy.done");
644 auto IsEmpty =
645 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
646 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000647
Alexey Bataev420d45b2015-04-14 05:11:24 +0000648 // Enter the loop body, making that address the current address.
649 auto EntryBB = Builder.GetInsertBlock();
650 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000651
652 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
653
654 llvm::PHINode *SrcElementPHI =
655 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
656 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
657 Address SrcElementCurrent =
658 Address(SrcElementPHI,
659 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
660
661 llvm::PHINode *DestElementPHI =
662 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
663 DestElementPHI->addIncoming(DestBegin, EntryBB);
664 Address DestElementCurrent =
665 Address(DestElementPHI,
666 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000667
Alexey Bataev420d45b2015-04-14 05:11:24 +0000668 // Emit copy.
669 CopyGen(DestElementCurrent, SrcElementCurrent);
670
671 // Shift the address forward by one element.
672 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000673 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000674 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000675 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000676 // Check whether we've reached the end.
677 auto Done =
678 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
679 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000680 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
681 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000682
683 // Done.
684 EmitBlock(DoneBB, /*IsFinished=*/true);
685}
686
John McCall7f416cc2015-09-08 08:05:57 +0000687void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
688 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000689 const VarDecl *SrcVD, const Expr *Copy) {
690 if (OriginalType->isArrayType()) {
691 auto *BO = dyn_cast<BinaryOperator>(Copy);
692 if (BO && BO->getOpcode() == BO_Assign) {
693 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000694 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
695 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
696 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000697 } else {
698 // For arrays with complex element types perform element by element
699 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000700 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000701 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000702 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000703 // Working with the single array element, so have to remap
704 // destination and source variables to corresponding array
705 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000706 CodeGenFunction::OMPPrivateScope Remap(*this);
707 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000708 return DestElement;
709 });
710 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000711 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000712 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000713 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000715 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 } else {
717 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000718 CodeGenFunction::OMPPrivateScope Remap(*this);
719 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
720 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000721 (void)Remap.Privatize();
722 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000723 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000724 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725}
726
Alexey Bataev69c62a92015-04-15 04:52:20 +0000727bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
728 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000729 if (!HaveInsertPoint())
730 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000731 bool FirstprivateIsLastprivate = false;
732 llvm::DenseSet<const VarDecl *> Lastprivates;
733 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
734 for (const auto *D : C->varlists())
735 Lastprivates.insert(
736 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
737 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000738 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000739 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
740 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
741 // Force emission of the firstprivate copy if the directive does not emit
742 // outlined function, like omp for, omp simd, omp distribute etc.
743 bool MustEmitFirstprivateCopy =
744 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000745 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000746 auto IRef = C->varlist_begin();
747 auto InitsRef = C->inits().begin();
748 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000749 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000750 bool ThisFirstprivateIsLastprivate =
751 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
752 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000753 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000754 !FD->getType()->isReferenceType()) {
755 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
756 ++IRef;
757 ++InitsRef;
758 continue;
759 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000760 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000761 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000762 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000763 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
764 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
765 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000766 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
767 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
768 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000769 LValue OriginalLVal = EmitLValue(&DRE);
770 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000771 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000772 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000773 // Emit VarDecl with copy init for arrays.
774 // Get the address of the original variable captured in current
775 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000776 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000777 auto Emission = EmitAutoVarAlloca(*VD);
778 auto *Init = VD->getInit();
779 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
780 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000781 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(),
782 Type);
783 EmitAggregateAssign(Dest, OriginalLVal, Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000784 } else {
785 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000786 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000787 [this, VDInit, Init](Address DestElement,
788 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000789 // Clean up any temporaries needed by the initialization.
790 RunCleanupsScope InitScope(*this);
791 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000792 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000793 EmitAnyExprToMem(Init, DestElement,
794 Init->getType().getQualifiers(),
795 /*IsInitializer*/ false);
796 LocalDeclMap.erase(VDInit);
797 });
798 }
799 EmitAutoVarCleanups(Emission);
800 return Emission.getAllocatedAddress();
801 });
802 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000803 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000804 // Emit private VarDecl with copy init.
805 // Remap temp VDInit variable to the address of the original
806 // variable
807 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000808 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000809 EmitDecl(*VD);
810 LocalDeclMap.erase(VDInit);
811 return GetAddrOfLocalVar(VD);
812 });
813 }
814 assert(IsRegistered &&
815 "firstprivate var already registered as private");
816 // Silence the warning about unused variable.
817 (void)IsRegistered;
818 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000819 ++IRef;
820 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000821 }
822 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000823 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000824}
825
Alexey Bataev03b340a2014-10-21 03:16:40 +0000826void CodeGenFunction::EmitOMPPrivateClause(
827 const OMPExecutableDirective &D,
828 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000829 if (!HaveInsertPoint())
830 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000831 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000832 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000833 auto IRef = C->varlist_begin();
834 for (auto IInit : C->private_copies()) {
835 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000836 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
837 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
838 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000839 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000840 // Emit private VarDecl with copy init.
841 EmitDecl(*VD);
842 return GetAddrOfLocalVar(VD);
843 });
844 assert(IsRegistered && "private var already registered as private");
845 // Silence the warning about unused variable.
846 (void)IsRegistered;
847 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000848 ++IRef;
849 }
850 }
851}
852
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000853bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000854 if (!HaveInsertPoint())
855 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000856 // threadprivate_var1 = master_threadprivate_var1;
857 // operator=(threadprivate_var2, master_threadprivate_var2);
858 // ...
859 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000860 llvm::DenseSet<const VarDecl *> CopiedVars;
861 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000862 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000863 auto IRef = C->varlist_begin();
864 auto ISrcRef = C->source_exprs().begin();
865 auto IDestRef = C->destination_exprs().begin();
866 for (auto *AssignOp : C->assignment_ops()) {
867 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000868 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000869 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000870 // Get the address of the master variable. If we are emitting code with
871 // TLS support, the address is passed from the master as field in the
872 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000873 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000874 if (getLangOpts().OpenMPUseTLS &&
875 getContext().getTargetInfo().isTLSSupported()) {
876 assert(CapturedStmtInfo->lookup(VD) &&
877 "Copyin threadprivates should have been captured!");
878 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
879 VK_LValue, (*IRef)->getExprLoc());
880 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000881 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000882 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000883 MasterAddr =
884 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
885 : CGM.GetAddrOfGlobal(VD),
886 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000887 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000888 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000889 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000890 if (CopiedVars.size() == 1) {
891 // At first check if current thread is a master thread. If it is, no
892 // need to copy data.
893 CopyBegin = createBasicBlock("copyin.not.master");
894 CopyEnd = createBasicBlock("copyin.not.master.end");
895 Builder.CreateCondBr(
896 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000897 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
898 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000899 CopyBegin, CopyEnd);
900 EmitBlock(CopyBegin);
901 }
902 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
903 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000904 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000905 }
906 ++IRef;
907 ++ISrcRef;
908 ++IDestRef;
909 }
910 }
911 if (CopyEnd) {
912 // Exit out of copying procedure for non-master thread.
913 EmitBlock(CopyEnd, /*IsFinished=*/true);
914 return true;
915 }
916 return false;
917}
918
Alexey Bataev38e89532015-04-16 04:54:05 +0000919bool CodeGenFunction::EmitOMPLastprivateClauseInit(
920 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000921 if (!HaveInsertPoint())
922 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000923 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000924 llvm::DenseSet<const VarDecl *> SIMDLCVs;
925 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
926 auto *LoopDirective = cast<OMPLoopDirective>(&D);
927 for (auto *C : LoopDirective->counters()) {
928 SIMDLCVs.insert(
929 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
930 }
931 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000932 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000933 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000934 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000935 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
936 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000937 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000938 auto IRef = C->varlist_begin();
939 auto IDestRef = C->destination_exprs().begin();
940 for (auto *IInit : C->private_copies()) {
941 // Keep the address of the original variable for future update at the end
942 // of the loop.
943 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000944 // Taskloops do not require additional initialization, it is done in
945 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000946 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
947 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000948 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000949 DeclRefExpr DRE(
950 const_cast<VarDecl *>(OrigVD),
951 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
952 OrigVD) != nullptr,
953 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
954 return EmitLValue(&DRE).getAddress();
955 });
956 // Check if the variable is also a firstprivate: in this case IInit is
957 // not generated. Initialization of this variable will happen in codegen
958 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000959 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000960 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000961 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
962 // Emit private VarDecl with copy init.
963 EmitDecl(*VD);
964 return GetAddrOfLocalVar(VD);
965 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000966 assert(IsRegistered &&
967 "lastprivate var already registered as private");
968 (void)IsRegistered;
969 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000970 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000971 ++IRef;
972 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 }
974 }
975 return HasAtLeastOneLastprivate;
976}
977
978void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000979 const OMPExecutableDirective &D, bool NoFinals,
980 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000981 if (!HaveInsertPoint())
982 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000983 // Emit following code:
984 // if (<IsLastIterCond>) {
985 // orig_var1 = private_orig_var1;
986 // ...
987 // orig_varn = private_orig_varn;
988 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000989 llvm::BasicBlock *ThenBB = nullptr;
990 llvm::BasicBlock *DoneBB = nullptr;
991 if (IsLastIterCond) {
992 ThenBB = createBasicBlock(".omp.lastprivate.then");
993 DoneBB = createBasicBlock(".omp.lastprivate.done");
994 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
995 EmitBlock(ThenBB);
996 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000997 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
998 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000999 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001000 auto IC = LoopDirective->counters().begin();
1001 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001002 auto *D =
1003 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1004 if (NoFinals)
1005 AlreadyEmittedVars.insert(D);
1006 else
1007 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001008 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001009 }
1010 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001011 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1012 auto IRef = C->varlist_begin();
1013 auto ISrcRef = C->source_exprs().begin();
1014 auto IDestRef = C->destination_exprs().begin();
1015 for (auto *AssignOp : C->assignment_ops()) {
1016 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1017 QualType Type = PrivateVD->getType();
1018 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1019 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1020 // If lastprivate variable is a loop control variable for loop-based
1021 // directive, update its value before copyin back to original
1022 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001023 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1024 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001025 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1026 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1027 // Get the address of the original variable.
1028 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1029 // Get the address of the private variable.
1030 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1031 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1032 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001033 Address(Builder.CreateLoad(PrivateAddr),
1034 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001035 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001036 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001037 ++IRef;
1038 ++ISrcRef;
1039 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001040 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001041 if (auto *PostUpdate = C->getPostUpdateExpr())
1042 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001043 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001044 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001045 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001046}
1047
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001048void CodeGenFunction::EmitOMPReductionClauseInit(
1049 const OMPExecutableDirective &D,
1050 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001051 if (!HaveInsertPoint())
1052 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001053 SmallVector<const Expr *, 4> Shareds;
1054 SmallVector<const Expr *, 4> Privates;
1055 SmallVector<const Expr *, 4> ReductionOps;
1056 SmallVector<const Expr *, 4> LHSs;
1057 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001058 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001059 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001060 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 auto ILHS = C->lhs_exprs().begin();
1062 auto IRHS = C->rhs_exprs().begin();
1063 for (const auto *Ref : C->varlists()) {
1064 Shareds.emplace_back(Ref);
1065 Privates.emplace_back(*IPriv);
1066 ReductionOps.emplace_back(*IRed);
1067 LHSs.emplace_back(*ILHS);
1068 RHSs.emplace_back(*IRHS);
1069 std::advance(IPriv, 1);
1070 std::advance(IRed, 1);
1071 std::advance(ILHS, 1);
1072 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001073 }
1074 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001075 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1076 unsigned Count = 0;
1077 auto ILHS = LHSs.begin();
1078 auto IRHS = RHSs.begin();
1079 auto IPriv = Privates.begin();
1080 for (const auto *IRef : Shareds) {
1081 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1082 // Emit private VarDecl with reduction init.
1083 RedCG.emitSharedLValue(*this, Count);
1084 RedCG.emitAggregateType(*this, Count);
1085 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1086 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1087 RedCG.getSharedLValue(Count),
1088 [&Emission](CodeGenFunction &CGF) {
1089 CGF.EmitAutoVarInit(Emission);
1090 return true;
1091 });
1092 EmitAutoVarCleanups(Emission);
1093 Address BaseAddr = RedCG.adjustPrivateAddress(
1094 *this, Count, Emission.getAllocatedAddress());
1095 bool IsRegistered = PrivateScope.addPrivate(
1096 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1097 assert(IsRegistered && "private var already registered as private");
1098 // Silence the warning about unused variable.
1099 (void)IsRegistered;
1100
1101 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1102 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001103 QualType Type = PrivateVD->getType();
1104 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1105 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001106 // Store the address of the original variable associated with the LHS
1107 // implicit variable.
1108 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1109 return RedCG.getSharedLValue(Count).getAddress();
1110 });
1111 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1112 return GetAddrOfLocalVar(PrivateVD);
1113 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001114 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1115 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 // Store the address of the original variable associated with the LHS
1117 // implicit variable.
1118 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1119 return RedCG.getSharedLValue(Count).getAddress();
1120 });
1121 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1122 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1123 ConvertTypeForMem(RHSVD->getType()),
1124 "rhs.begin");
1125 });
1126 } else {
1127 QualType Type = PrivateVD->getType();
1128 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1129 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1130 // Store the address of the original variable associated with the LHS
1131 // implicit variable.
1132 if (IsArray) {
1133 OriginalAddr = Builder.CreateElementBitCast(
1134 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1135 }
1136 PrivateScope.addPrivate(
1137 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1138 PrivateScope.addPrivate(
1139 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1140 return IsArray
1141 ? Builder.CreateElementBitCast(
1142 GetAddrOfLocalVar(PrivateVD),
1143 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1144 : GetAddrOfLocalVar(PrivateVD);
1145 });
1146 }
1147 ++ILHS;
1148 ++IRHS;
1149 ++IPriv;
1150 ++Count;
1151 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001152}
1153
1154void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001155 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001156 if (!HaveInsertPoint())
1157 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001158 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001159 llvm::SmallVector<const Expr *, 8> LHSExprs;
1160 llvm::SmallVector<const Expr *, 8> RHSExprs;
1161 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001162 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001163 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001165 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001166 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1167 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1168 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1169 }
1170 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001171 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1172 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001173 ReductionKind == OMPD_simd;
1174 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001175 // Emit nowait reduction if nowait clause is present or directive is a
1176 // parallel directive (it always has implicit barrier).
1177 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001178 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001179 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001180 }
1181}
1182
Alexey Bataev61205072016-03-02 04:57:40 +00001183static void emitPostUpdateForReductionClause(
1184 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1185 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1186 if (!CGF.HaveInsertPoint())
1187 return;
1188 llvm::BasicBlock *DoneBB = nullptr;
1189 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1190 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1191 if (!DoneBB) {
1192 if (auto *Cond = CondGen(CGF)) {
1193 // If the first post-update expression is found, emit conditional
1194 // block if it was requested.
1195 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1196 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1197 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1198 CGF.EmitBlock(ThenBB);
1199 }
1200 }
1201 CGF.EmitIgnoredExpr(PostUpdate);
1202 }
1203 }
1204 if (DoneBB)
1205 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1206}
1207
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001208namespace {
1209/// Codegen lambda for appending distribute lower and upper bounds to outlined
1210/// parallel function. This is necessary for combined constructs such as
1211/// 'distribute parallel for'
1212typedef llvm::function_ref<void(CodeGenFunction &,
1213 const OMPExecutableDirective &,
1214 llvm::SmallVectorImpl<llvm::Value *> &)>
1215 CodeGenBoundParametersTy;
1216} // anonymous namespace
1217
1218static void emitCommonOMPParallelDirective(
1219 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1220 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1221 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001222 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1223 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1224 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001225 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001226 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001227 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1228 /*IgnoreResultAssign*/ true);
1229 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1230 CGF, NumThreads, NumThreadsClause->getLocStart());
1231 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001232 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001233 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001234 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1235 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1236 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001237 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001238 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1239 if (C->getNameModifier() == OMPD_unknown ||
1240 C->getNameModifier() == OMPD_parallel) {
1241 IfCond = C->getCondition();
1242 break;
1243 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001244 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001245
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001246 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001247 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001248 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1249 // lower and upper bounds with the pragma 'for' chunking mechanism.
1250 // The following lambda takes care of appending the lower and upper bound
1251 // parameters when necessary
1252 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001253 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001254 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001255 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001256}
1257
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001258static void emitEmptyBoundParameters(CodeGenFunction &,
1259 const OMPExecutableDirective &,
1260 llvm::SmallVectorImpl<llvm::Value *> &) {}
1261
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001262void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001264 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001266 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001267 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1268 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001269 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001270 // propagation master's thread values of threadprivate variables to local
1271 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001272 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1273 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1274 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001275 }
1276 CGF.EmitOMPPrivateClause(S, PrivateScope);
1277 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1278 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001279 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001280 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001281 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001282 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1283 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001284 emitPostUpdateForReductionClause(
1285 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001286}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001287
Alexey Bataev0f34da12015-07-02 04:17:07 +00001288void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1289 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001290 RunCleanupsScope BodyScope(*this);
1291 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001292 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001293 EmitIgnoredExpr(I);
1294 }
Alexander Musman3276a272015-03-21 10:12:56 +00001295 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001296 // In distribute directives only loop counters may be marked as linear, no
1297 // need to generate the code for them.
1298 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1299 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1300 for (auto *U : C->updates())
1301 EmitIgnoredExpr(U);
1302 }
Alexander Musman3276a272015-03-21 10:12:56 +00001303 }
1304
Alexander Musmana5f070a2014-10-01 06:03:56 +00001305 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001306 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001307 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001308 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001310 // The end (updates/cleanups).
1311 EmitBlock(Continue.getBlock());
1312 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001313}
1314
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315void CodeGenFunction::EmitOMPInnerLoop(
1316 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1317 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001318 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1319 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001320 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001321
1322 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001323 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001324 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001325 const SourceRange &R = S.getSourceRange();
1326 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1327 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001328
1329 // If there are any cleanups between here and the loop-exit scope,
1330 // create a block to stage a loop exit along.
1331 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001332 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001333 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001334
Alexander Musmand196ef22014-10-07 08:57:09 +00001335 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336
Alexey Bataev2df54a02015-03-12 08:53:29 +00001337 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001338 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001339 if (ExitBlock != LoopExit.getBlock()) {
1340 EmitBlock(ExitBlock);
1341 EmitBranchThroughCleanup(LoopExit);
1342 }
1343
1344 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001345 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001346
1347 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001348 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001349 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1350
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001352
1353 // Emit "IV = IV + 1" and a back-edge to the condition block.
1354 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001355 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001356 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001357 BreakContinueStack.pop_back();
1358 EmitBranch(CondBlock);
1359 LoopStack.pop();
1360 // Emit the fall-through block.
1361 EmitBlock(LoopExit.getBlock());
1362}
1363
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001364bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001365 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001366 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001367 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001368 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001369 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001370 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001371 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001372 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001373 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1374 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1375 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1376 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1377 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1378 VD->getInit()->getType(), VK_LValue,
1379 VD->getInit()->getExprLoc());
1380 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1381 VD->getType()),
1382 /*capturedByInit=*/false);
1383 EmitAutoVarCleanups(Emission);
1384 } else
1385 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001386 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001387 // Emit the linear steps for the linear clauses.
1388 // If a step is not constant, it is pre-calculated before the loop.
1389 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1390 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001391 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001392 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001393 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001394 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001395 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001396 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001397}
1398
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001399void CodeGenFunction::EmitOMPLinearClauseFinal(
1400 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001401 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001402 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001403 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001404 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001405 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001406 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001407 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001408 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001409 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001411 // If the first post-update expression is found, emit conditional
1412 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001413 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1414 DoneBB = createBasicBlock(".omp.linear.pu.done");
1415 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1416 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001417 }
1418 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001419 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1420 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001421 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001422 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001423 Address OrigAddr = EmitLValue(&DRE).getAddress();
1424 CodeGenFunction::OMPPrivateScope VarScope(*this);
1425 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001426 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001427 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001428 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001429 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001430 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001431 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001432 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001433 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001434 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001435}
1436
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001437static void emitAlignedClause(CodeGenFunction &CGF,
1438 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001439 if (!CGF.HaveInsertPoint())
1440 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001441 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001442 unsigned ClauseAlignment = 0;
1443 if (auto AlignmentExpr = Clause->getAlignment()) {
1444 auto AlignmentCI =
1445 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1446 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001447 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001448 for (auto E : Clause->varlists()) {
1449 unsigned Alignment = ClauseAlignment;
1450 if (Alignment == 0) {
1451 // OpenMP [2.8.1, Description]
1452 // If no optional parameter is specified, implementation-defined default
1453 // alignments for SIMD instructions on the target platforms are assumed.
1454 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001455 CGF.getContext()
1456 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1457 E->getType()->getPointeeType()))
1458 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001459 }
1460 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1461 "alignment is not power of 2");
1462 if (Alignment != 0) {
1463 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1464 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1465 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001466 }
1467 }
1468}
1469
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001470void CodeGenFunction::EmitOMPPrivateLoopCounters(
1471 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1472 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001473 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001474 auto I = S.private_counters().begin();
1475 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001476 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1477 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001478 // Emit var without initialization.
1479 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1480 EmitAutoVarCleanups(VarEmission);
1481 LocalDeclMap.erase(PrivateVD);
1482 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1483 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001484 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001485 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1486 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001487 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001488 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1489 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1490 E->getType(), VK_LValue, E->getExprLoc());
1491 return EmitLValue(&DRE).getAddress();
1492 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001493 } else {
1494 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1495 return VarEmission.getAllocatedAddress();
1496 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001497 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001498 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001499 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001500}
1501
Alexey Bataev62dbb972015-04-22 11:59:37 +00001502static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1503 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1504 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001505 if (!CGF.HaveInsertPoint())
1506 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001507 {
1508 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001509 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001510 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001511 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001512 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001513 CGF.EmitIgnoredExpr(I);
1514 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001515 }
1516 // Check that loop is executed at least one time.
1517 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1518}
1519
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001520void CodeGenFunction::EmitOMPLinearClause(
1521 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1522 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001523 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001524 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1525 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1526 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1527 for (auto *C : LoopDirective->counters()) {
1528 SIMDLCVs.insert(
1529 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1530 }
1531 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001532 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001533 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001534 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1536 auto *PrivateVD =
1537 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001538 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1539 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1540 // Emit private VarDecl with copy init.
1541 EmitVarDecl(*PrivateVD);
1542 return GetAddrOfLocalVar(PrivateVD);
1543 });
1544 assert(IsRegistered && "linear var already registered as private");
1545 // Silence the warning about unused variable.
1546 (void)IsRegistered;
1547 } else
1548 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001549 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001550 }
1551 }
1552}
1553
Alexey Bataev45bfad52015-08-21 12:19:04 +00001554static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001555 const OMPExecutableDirective &D,
1556 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001557 if (!CGF.HaveInsertPoint())
1558 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001559 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001560 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1561 /*ignoreResult=*/true);
1562 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1563 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1564 // In presence of finite 'safelen', it may be unsafe to mark all
1565 // the memory instructions parallel, because loop-carried
1566 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001567 if (!IsMonotonic)
1568 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001569 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001570 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1571 /*ignoreResult=*/true);
1572 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001573 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001574 // In presence of finite 'safelen', it may be unsafe to mark all
1575 // the memory instructions parallel, because loop-carried
1576 // dependences of 'safelen' iterations are possible.
1577 CGF.LoopStack.setParallel(false);
1578 }
1579}
1580
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001581void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1582 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001583 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001584 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001585 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001586 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001587}
1588
Alexey Bataevef549a82016-03-09 09:49:09 +00001589void CodeGenFunction::EmitOMPSimdFinal(
1590 const OMPLoopDirective &D,
1591 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001592 if (!HaveInsertPoint())
1593 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001594 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001595 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001596 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001597 for (auto F : D.finals()) {
1598 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001599 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1600 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1601 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1602 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001603 if (!DoneBB) {
1604 if (auto *Cond = CondGen(*this)) {
1605 // If the first post-update expression is found, emit conditional
1606 // block if it was requested.
1607 auto *ThenBB = createBasicBlock(".omp.final.then");
1608 DoneBB = createBasicBlock(".omp.final.done");
1609 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1610 EmitBlock(ThenBB);
1611 }
1612 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001613 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001614 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001615 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001616 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001617 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1618 /*RefersToEnclosingVariableOrCapture=*/false,
1619 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1620 OrigAddr = EmitLValue(&DRE).getAddress();
1621 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001622 OMPPrivateScope VarScope(*this);
1623 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001624 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001625 (void)VarScope.Privatize();
1626 EmitIgnoredExpr(F);
1627 }
1628 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001629 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001630 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001631 if (DoneBB)
1632 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001633}
1634
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001635static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1636 const OMPLoopDirective &S,
1637 CodeGenFunction::JumpDest LoopExit) {
1638 CGF.EmitOMPLoopBody(S, LoopExit);
1639 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001640}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001641
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001642/// Emit a helper variable and return corresponding lvalue.
1643static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1644 const DeclRefExpr *Helper) {
1645 auto VDecl = cast<VarDecl>(Helper->getDecl());
1646 CGF.EmitVarDecl(*VDecl);
1647 return CGF.EmitLValue(Helper);
1648}
1649
Alexey Bataevf8365372017-11-17 17:57:25 +00001650static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1651 PrePostActionTy &Action) {
1652 Action.Enter(CGF);
1653 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1654 "Expected simd directive");
1655 OMPLoopScope PreInitScope(CGF, S);
1656 // if (PreCond) {
1657 // for (IV in 0..LastIteration) BODY;
1658 // <Final counter/linear vars updates>;
1659 // }
1660 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001661 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1662 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1663 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1664 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1665 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1666 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001667
Alexey Bataevf8365372017-11-17 17:57:25 +00001668 // Emit: if (PreCond) - begin.
1669 // If the condition constant folds and can be elided, avoid emitting the
1670 // whole loop.
1671 bool CondConstant;
1672 llvm::BasicBlock *ContBlock = nullptr;
1673 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1674 if (!CondConstant)
1675 return;
1676 } else {
1677 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1678 ContBlock = CGF.createBasicBlock("simd.if.end");
1679 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1680 CGF.getProfileCount(&S));
1681 CGF.EmitBlock(ThenBlock);
1682 CGF.incrementProfileCounter(&S);
1683 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001684
Alexey Bataevf8365372017-11-17 17:57:25 +00001685 // Emit the loop iteration variable.
1686 const Expr *IVExpr = S.getIterationVariable();
1687 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1688 CGF.EmitVarDecl(*IVDecl);
1689 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001690
Alexey Bataevf8365372017-11-17 17:57:25 +00001691 // Emit the iterations count variable.
1692 // If it is not a variable, Sema decided to calculate iterations count on
1693 // each iteration (e.g., it is foldable into a constant).
1694 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1695 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1696 // Emit calculation of the iterations count.
1697 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1698 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001699
Alexey Bataevf8365372017-11-17 17:57:25 +00001700 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001701
Alexey Bataevf8365372017-11-17 17:57:25 +00001702 emitAlignedClause(CGF, S);
1703 (void)CGF.EmitOMPLinearClauseInit(S);
1704 {
1705 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1706 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1707 CGF.EmitOMPLinearClause(S, LoopScope);
1708 CGF.EmitOMPPrivateClause(S, LoopScope);
1709 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1710 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1711 (void)LoopScope.Privatize();
1712 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1713 S.getInc(),
1714 [&S](CodeGenFunction &CGF) {
1715 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1716 CGF.EmitStopPoint(&S);
1717 },
1718 [](CodeGenFunction &) {});
1719 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001720 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001721 // Emit final copy of the lastprivate variables at the end of loops.
1722 if (HasLastprivateClause)
1723 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1724 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1725 emitPostUpdateForReductionClause(
1726 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1727 }
1728 CGF.EmitOMPLinearClauseFinal(
1729 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1730 // Emit: if (PreCond) - end.
1731 if (ContBlock) {
1732 CGF.EmitBranch(ContBlock);
1733 CGF.EmitBlock(ContBlock, true);
1734 }
1735}
1736
1737void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1738 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1739 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001740 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001741 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001742 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001743}
1744
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001745void CodeGenFunction::EmitOMPOuterLoop(
1746 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1747 CodeGenFunction::OMPPrivateScope &LoopScope,
1748 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1749 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1750 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001751 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001752
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001753 const Expr *IVExpr = S.getIterationVariable();
1754 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1755 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1756
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001757 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1758
1759 // Start the loop with a block that tests the condition.
1760 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1761 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001762 const SourceRange &R = S.getSourceRange();
1763 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1764 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001765
1766 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001767 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001768 // UB = min(UB, GlobalUB) or
1769 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1770 // 'distribute parallel for')
1771 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001772 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001773 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001774 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001775 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001777 BoolCondVal =
1778 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1779 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001780 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001781
1782 // If there are any cleanups between here and the loop-exit scope,
1783 // create a block to stage a loop exit along.
1784 auto ExitBlock = LoopExit.getBlock();
1785 if (LoopScope.requiresCleanups())
1786 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1787
1788 auto LoopBody = createBasicBlock("omp.dispatch.body");
1789 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1790 if (ExitBlock != LoopExit.getBlock()) {
1791 EmitBlock(ExitBlock);
1792 EmitBranchThroughCleanup(LoopExit);
1793 }
1794 EmitBlock(LoopBody);
1795
Alexander Musman92bdaab2015-03-12 13:37:50 +00001796 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1797 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001798 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001799 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001800
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001801 // Create a block for the increment.
1802 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1803 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1804
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001805 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1806 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001807 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1808 LoopStack.setParallel(!IsMonotonic);
1809 else
1810 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001811
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001812 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001813
1814 // when 'distribute' is not combined with a 'for':
1815 // while (idx <= UB) { BODY; ++idx; }
1816 // when 'distribute' is combined with a 'for'
1817 // (e.g. 'distribute parallel for')
1818 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1819 EmitOMPInnerLoop(
1820 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1821 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1822 CodeGenLoop(CGF, S, LoopExit);
1823 },
1824 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1825 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1826 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001827
1828 EmitBlock(Continue.getBlock());
1829 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001830 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001831 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001832 EmitIgnoredExpr(LoopArgs.NextLB);
1833 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001834 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001835
1836 EmitBranch(CondBlock);
1837 LoopStack.pop();
1838 // Emit the fall-through block.
1839 EmitBlock(LoopExit.getBlock());
1840
1841 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001842 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1843 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001844 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1845 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001846 };
1847 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001848}
1849
1850void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001851 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001852 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001853 const OMPLoopArguments &LoopArgs,
1854 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001855 auto &RT = CGM.getOpenMPRuntime();
1856
1857 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001858 const bool DynamicOrOrdered =
1859 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001860
1861 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001862 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001863 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001864 "static non-chunked schedule does not need outer loop");
1865
1866 // Emit outer loop.
1867 //
1868 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1869 // When schedule(dynamic,chunk_size) is specified, the iterations are
1870 // distributed to threads in the team in chunks as the threads request them.
1871 // Each thread executes a chunk of iterations, then requests another chunk,
1872 // until no chunks remain to be distributed. Each chunk contains chunk_size
1873 // iterations, except for the last chunk to be distributed, which may have
1874 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1875 //
1876 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1877 // to threads in the team in chunks as the executing threads request them.
1878 // Each thread executes a chunk of iterations, then requests another chunk,
1879 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1880 // each chunk is proportional to the number of unassigned iterations divided
1881 // by the number of threads in the team, decreasing to 1. For a chunk_size
1882 // with value k (greater than 1), the size of each chunk is determined in the
1883 // same way, with the restriction that the chunks do not contain fewer than k
1884 // iterations (except for the last chunk to be assigned, which may have fewer
1885 // than k iterations).
1886 //
1887 // When schedule(auto) is specified, the decision regarding scheduling is
1888 // delegated to the compiler and/or runtime system. The programmer gives the
1889 // implementation the freedom to choose any possible mapping of iterations to
1890 // threads in the team.
1891 //
1892 // When schedule(runtime) is specified, the decision regarding scheduling is
1893 // deferred until run time, and the schedule and chunk size are taken from the
1894 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1895 // implementation defined
1896 //
1897 // while(__kmpc_dispatch_next(&LB, &UB)) {
1898 // idx = LB;
1899 // while (idx <= UB) { BODY; ++idx;
1900 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1901 // } // inner loop
1902 // }
1903 //
1904 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1905 // When schedule(static, chunk_size) is specified, iterations are divided into
1906 // chunks of size chunk_size, and the chunks are assigned to the threads in
1907 // the team in a round-robin fashion in the order of the thread number.
1908 //
1909 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1910 // while (idx <= UB) { BODY; ++idx; } // inner loop
1911 // LB = LB + ST;
1912 // UB = UB + ST;
1913 // }
1914 //
1915
1916 const Expr *IVExpr = S.getIterationVariable();
1917 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1918 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1919
1920 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001921 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1922 llvm::Value *LBVal = DispatchBounds.first;
1923 llvm::Value *UBVal = DispatchBounds.second;
1924 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1925 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001926 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001927 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001928 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001929 CGOpenMPRuntime::StaticRTInput StaticInit(
1930 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1931 LoopArgs.ST, LoopArgs.Chunk);
1932 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1933 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001934 }
1935
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001936 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1937 const unsigned IVSize,
1938 const bool IVSigned) {
1939 if (Ordered) {
1940 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1941 IVSigned);
1942 }
1943 };
1944
1945 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1946 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1947 OuterLoopArgs.IncExpr = S.getInc();
1948 OuterLoopArgs.Init = S.getInit();
1949 OuterLoopArgs.Cond = S.getCond();
1950 OuterLoopArgs.NextLB = S.getNextLowerBound();
1951 OuterLoopArgs.NextUB = S.getNextUpperBound();
1952 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1953 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001954}
1955
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001956static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1957 const unsigned IVSize, const bool IVSigned) {}
1958
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001959void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001960 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1961 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1962 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001963
1964 auto &RT = CGM.getOpenMPRuntime();
1965
1966 // Emit outer loop.
1967 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1968 // dynamic
1969 //
1970
1971 const Expr *IVExpr = S.getIterationVariable();
1972 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1973 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1974
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001975 CGOpenMPRuntime::StaticRTInput StaticInit(
1976 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1977 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1978 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001979
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001980 // for combined 'distribute' and 'for' the increment expression of distribute
1981 // is store in DistInc. For 'distribute' alone, it is in Inc.
1982 Expr *IncExpr;
1983 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1984 IncExpr = S.getDistInc();
1985 else
1986 IncExpr = S.getInc();
1987
1988 // this routine is shared by 'omp distribute parallel for' and
1989 // 'omp distribute': select the right EUB expression depending on the
1990 // directive
1991 OMPLoopArguments OuterLoopArgs;
1992 OuterLoopArgs.LB = LoopArgs.LB;
1993 OuterLoopArgs.UB = LoopArgs.UB;
1994 OuterLoopArgs.ST = LoopArgs.ST;
1995 OuterLoopArgs.IL = LoopArgs.IL;
1996 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1997 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1998 ? S.getCombinedEnsureUpperBound()
1999 : S.getEnsureUpperBound();
2000 OuterLoopArgs.IncExpr = IncExpr;
2001 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2002 ? S.getCombinedInit()
2003 : S.getInit();
2004 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2005 ? S.getCombinedCond()
2006 : S.getCond();
2007 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2008 ? S.getCombinedNextLowerBound()
2009 : S.getNextLowerBound();
2010 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2011 ? S.getCombinedNextUpperBound()
2012 : S.getNextUpperBound();
2013
2014 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2015 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2016 emitEmptyOrdered);
2017}
2018
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002019static std::pair<LValue, LValue>
2020emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2021 const OMPExecutableDirective &S) {
2022 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2023 LValue LB =
2024 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2025 LValue UB =
2026 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2027
2028 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2029 // parallel for') we need to use the 'distribute'
2030 // chunk lower and upper bounds rather than the whole loop iteration
2031 // space. These are parameters to the outlined function for 'parallel'
2032 // and we copy the bounds of the previous schedule into the
2033 // the current ones.
2034 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2035 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002036 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2037 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002038 PrevLBVal = CGF.EmitScalarConversion(
2039 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002040 LS.getIterationVariable()->getType(),
2041 LS.getPrevLowerBoundVariable()->getExprLoc());
2042 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2043 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002044 PrevUBVal = CGF.EmitScalarConversion(
2045 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002046 LS.getIterationVariable()->getType(),
2047 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002048
2049 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2050 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2051
2052 return {LB, UB};
2053}
2054
2055/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2056/// we need to use the LB and UB expressions generated by the worksharing
2057/// code generation support, whereas in non combined situations we would
2058/// just emit 0 and the LastIteration expression
2059/// This function is necessary due to the difference of the LB and UB
2060/// types for the RT emission routines for 'for_static_init' and
2061/// 'for_dispatch_init'
2062static std::pair<llvm::Value *, llvm::Value *>
2063emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2064 const OMPExecutableDirective &S,
2065 Address LB, Address UB) {
2066 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2067 const Expr *IVExpr = LS.getIterationVariable();
2068 // when implementing a dynamic schedule for a 'for' combined with a
2069 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2070 // is not normalized as each team only executes its own assigned
2071 // distribute chunk
2072 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002073 llvm::Value *LBVal =
2074 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2075 llvm::Value *UBVal =
2076 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002077 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002078}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002079
2080static void emitDistributeParallelForDistributeInnerBoundParams(
2081 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2082 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2083 const auto &Dir = cast<OMPLoopDirective>(S);
2084 LValue LB =
2085 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2086 auto LBCast = CGF.Builder.CreateIntCast(
2087 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2088 CapturedVars.push_back(LBCast);
2089 LValue UB =
2090 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2091
2092 auto UBCast = CGF.Builder.CreateIntCast(
2093 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2094 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002095}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002096
2097static void
2098emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2099 const OMPLoopDirective &S,
2100 CodeGenFunction::JumpDest LoopExit) {
2101 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2102 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002103 bool HasCancel = false;
2104 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2105 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2106 HasCancel = D->hasCancel();
2107 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2108 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002109 else if (const auto *D =
2110 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2111 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002112 }
2113 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2114 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002115 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2116 emitDistributeParallelForInnerBounds,
2117 emitDistributeParallelForDispatchBounds);
2118 };
2119
2120 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002121 CGF, S,
2122 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2123 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002125}
2126
Carlo Bertolli9925f152016-06-27 14:55:37 +00002127void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2128 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002129 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2130 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2131 S.getDistInc());
2132 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002133 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002134 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002135}
2136
Kelvin Li4a39add2016-07-05 05:00:15 +00002137void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2138 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002139 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2140 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2141 S.getDistInc());
2142 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002143 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002144 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002145}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002146
2147void CodeGenFunction::EmitOMPDistributeSimdDirective(
2148 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002149 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2150 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2151 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002152 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002153 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002154}
2155
Alexey Bataevf8365372017-11-17 17:57:25 +00002156void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2157 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2158 // Emit SPMD target parallel for region as a standalone region.
2159 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2160 emitOMPSimdRegion(CGF, S, Action);
2161 };
2162 llvm::Function *Fn;
2163 llvm::Constant *Addr;
2164 // Emit target region as a standalone region.
2165 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2166 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2167 assert(Fn && Addr && "Target device function emission failed.");
2168}
2169
Kelvin Li986330c2016-07-20 22:57:10 +00002170void CodeGenFunction::EmitOMPTargetSimdDirective(
2171 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002172 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2173 emitOMPSimdRegion(CGF, S, Action);
2174 };
2175 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002176}
2177
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002178namespace {
2179 struct ScheduleKindModifiersTy {
2180 OpenMPScheduleClauseKind Kind;
2181 OpenMPScheduleClauseModifier M1;
2182 OpenMPScheduleClauseModifier M2;
2183 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2184 OpenMPScheduleClauseModifier M1,
2185 OpenMPScheduleClauseModifier M2)
2186 : Kind(Kind), M1(M1), M2(M2) {}
2187 };
2188} // namespace
2189
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002190bool CodeGenFunction::EmitOMPWorksharingLoop(
2191 const OMPLoopDirective &S, Expr *EUB,
2192 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2193 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002194 // Emit the loop iteration variable.
2195 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2196 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2197 EmitVarDecl(*IVDecl);
2198
2199 // Emit the iterations count variable.
2200 // If it is not a variable, Sema decided to calculate iterations count on each
2201 // iteration (e.g., it is foldable into a constant).
2202 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2203 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2204 // Emit calculation of the iterations count.
2205 EmitIgnoredExpr(S.getCalcLastIteration());
2206 }
2207
2208 auto &RT = CGM.getOpenMPRuntime();
2209
Alexey Bataev38e89532015-04-16 04:54:05 +00002210 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002211 // Check pre-condition.
2212 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002213 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002214 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002215 // If the condition constant folds and can be elided, avoid emitting the
2216 // whole loop.
2217 bool CondConstant;
2218 llvm::BasicBlock *ContBlock = nullptr;
2219 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2220 if (!CondConstant)
2221 return false;
2222 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002223 auto *ThenBlock = createBasicBlock("omp.precond.then");
2224 ContBlock = createBasicBlock("omp.precond.end");
2225 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002226 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002227 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002228 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002229 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002230
Alexey Bataevea33dee2018-02-15 23:39:43 +00002231 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002232 bool Ordered = false;
2233 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2234 if (OrderedClause->getNumForLoops())
2235 RT.emitDoacrossInit(*this, S);
2236 else
2237 Ordered = true;
2238 }
2239
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002240 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002241 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002242 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002243 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002244
2245 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2246 LValue LB = Bounds.first;
2247 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002248 LValue ST =
2249 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2250 LValue IL =
2251 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2252
Alexander Musmanc6388682014-12-15 07:07:06 +00002253 // Emit 'then' code.
2254 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002255 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002256 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002257 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002258 // initialization of firstprivate variables and post-update of
2259 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002260 CGM.getOpenMPRuntime().emitBarrierCall(
2261 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2262 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002263 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002264 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002265 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002266 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002267 EmitOMPPrivateLoopCounters(S, LoopScope);
2268 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002269 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002270
2271 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002272 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002273 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002274 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002275 ScheduleKind.Schedule = C->getScheduleKind();
2276 ScheduleKind.M1 = C->getFirstScheduleModifier();
2277 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002278 if (const auto *Ch = C->getChunkSize()) {
2279 Chunk = EmitScalarExpr(Ch);
2280 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2281 S.getIterationVariable()->getType(),
2282 S.getLocStart());
2283 }
2284 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002285 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2286 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002287 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2288 // If the static schedule kind is specified or if the ordered clause is
2289 // specified, and if no monotonic modifier is specified, the effect will
2290 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002291 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002292 /* Chunked */ Chunk != nullptr) &&
2293 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002294 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2295 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002296 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2297 // When no chunk_size is specified, the iteration space is divided into
2298 // chunks that are approximately equal in size, and at most one chunk is
2299 // distributed to each thread. Note that the size of the chunks is
2300 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002301 CGOpenMPRuntime::StaticRTInput StaticInit(
2302 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2303 UB.getAddress(), ST.getAddress());
2304 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2305 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002306 auto LoopExit =
2307 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002308 // UB = min(UB, GlobalUB);
2309 EmitIgnoredExpr(S.getEnsureUpperBound());
2310 // IV = LB;
2311 EmitIgnoredExpr(S.getInit());
2312 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002313 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2314 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002315 [&S, LoopExit](CodeGenFunction &CGF) {
2316 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002317 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002318 },
2319 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002320 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002321 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002322 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002323 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2324 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002325 };
2326 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002327 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002328 const bool IsMonotonic =
2329 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2330 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2331 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2332 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002333 // Emit the outer loop, which requests its work chunk [LB..UB] from
2334 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002335 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2336 ST.getAddress(), IL.getAddress(),
2337 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002338 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002339 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002340 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002341 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2342 EmitOMPSimdFinal(S,
2343 [&](CodeGenFunction &CGF) -> llvm::Value * {
2344 return CGF.Builder.CreateIsNotNull(
2345 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2346 });
2347 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002348 EmitOMPReductionClauseFinal(
2349 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2350 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2351 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002352 // Emit post-update of the reduction variables if IsLastIter != 0.
2353 emitPostUpdateForReductionClause(
2354 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2355 return CGF.Builder.CreateIsNotNull(
2356 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2357 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002358 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2359 if (HasLastprivateClause)
2360 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002361 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2362 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002363 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002364 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002365 return CGF.Builder.CreateIsNotNull(
2366 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2367 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002368 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002369 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002370 if (ContBlock) {
2371 EmitBranch(ContBlock);
2372 EmitBlock(ContBlock, true);
2373 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002375 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002376}
2377
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002378/// The following two functions generate expressions for the loop lower
2379/// and upper bounds in case of static and dynamic (dispatch) schedule
2380/// of the associated 'for' or 'distribute' loop.
2381static std::pair<LValue, LValue>
2382emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2383 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2384 LValue LB =
2385 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2386 LValue UB =
2387 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2388 return {LB, UB};
2389}
2390
2391/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2392/// consider the lower and upper bound expressions generated by the
2393/// worksharing loop support, but we use 0 and the iteration space size as
2394/// constants
2395static std::pair<llvm::Value *, llvm::Value *>
2396emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2397 Address LB, Address UB) {
2398 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2399 const Expr *IVExpr = LS.getIterationVariable();
2400 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2401 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2402 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2403 return {LBVal, UBVal};
2404}
2405
Alexander Musmanc6388682014-12-15 07:07:06 +00002406void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002407 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002408 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2409 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002410 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002411 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2412 emitForLoopBounds,
2413 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002414 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002415 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002416 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002417 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2418 S.hasCancel());
2419 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002420
2421 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002422 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002423 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2424 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002425}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002426
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002427void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002428 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002429 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2430 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002431 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2432 emitForLoopBounds,
2433 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002434 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002435 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002436 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002437 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2438 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002439
2440 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002441 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002442 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2443 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002444}
2445
Alexey Bataev2df54a02015-03-12 08:53:29 +00002446static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2447 const Twine &Name,
2448 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002449 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002450 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002451 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002452 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002453}
2454
Alexey Bataev3392d762016-02-16 11:18:12 +00002455void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002456 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2457 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002458 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002459 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2460 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002461 auto &C = CGF.CGM.getContext();
2462 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2463 // Emit helper vars inits.
2464 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2465 CGF.Builder.getInt32(0));
2466 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2467 : CGF.Builder.getInt32(0);
2468 LValue UB =
2469 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2470 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2471 CGF.Builder.getInt32(1));
2472 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2473 CGF.Builder.getInt32(0));
2474 // Loop counter.
2475 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2476 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2477 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2478 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2479 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2480 // Generate condition for loop.
2481 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002482 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 // Increment for loop counter.
2484 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002485 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002486 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2487 // Iterate through all sections and emit a switch construct:
2488 // switch (IV) {
2489 // case 0:
2490 // <SectionStmt[0]>;
2491 // break;
2492 // ...
2493 // case <NumSection> - 1:
2494 // <SectionStmt[<NumSection> - 1]>;
2495 // break;
2496 // }
2497 // .omp.sections.exit:
2498 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002499 auto *SwitchStmt =
2500 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2501 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002502 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002503 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002504 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002505 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2506 CGF.EmitBlock(CaseBB);
2507 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002508 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002509 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002510 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002511 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002512 } else {
2513 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2514 CGF.EmitBlock(CaseBB);
2515 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2516 CGF.EmitStmt(Stmt);
2517 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002518 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002519 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002520 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002521
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002522 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2523 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002524 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002525 // initialization of firstprivate variables and post-update of lastprivate
2526 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002527 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2528 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2529 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002530 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002531 CGF.EmitOMPPrivateClause(S, LoopScope);
2532 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2533 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2534 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002535
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002536 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002537 OpenMPScheduleTy ScheduleKind;
2538 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002539 CGOpenMPRuntime::StaticRTInput StaticInit(
2540 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2541 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002542 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002543 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002544 // UB = min(UB, GlobalUB);
2545 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2546 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2547 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2548 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2549 // IV = LB;
2550 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2551 // while (idx <= UB) { BODY; ++idx; }
2552 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2553 [](CodeGenFunction &) {});
2554 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002555 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002556 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2557 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002558 };
2559 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002560 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002561 // Emit post-update of the reduction variables if IsLastIter != 0.
2562 emitPostUpdateForReductionClause(
2563 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2564 return CGF.Builder.CreateIsNotNull(
2565 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2566 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002567
2568 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2569 if (HasLastprivates)
2570 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002571 S, /*NoFinals=*/false,
2572 CGF.Builder.CreateIsNotNull(
2573 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002574 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002575
2576 bool HasCancel = false;
2577 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2578 HasCancel = OSD->hasCancel();
2579 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2580 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002581 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002582 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2583 HasCancel);
2584 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2585 // clause. Otherwise the barrier will be generated by the codegen for the
2586 // directive.
2587 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002588 // Emit implicit barrier to synchronize threads and avoid data races on
2589 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002590 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2591 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002592 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002593}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002594
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002595void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002596 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002597 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002598 EmitSections(S);
2599 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002600 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002601 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002602 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2603 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002604 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002605}
2606
2607void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002608 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002609 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002611 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002612 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2613 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002614}
2615
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002616void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002617 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002618 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002619 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002620 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002621 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002622 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002623 // Build a list of copyprivate variables along with helper expressions
2624 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002625 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002626 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002627 DestExprs.append(C->destination_exprs().begin(),
2628 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002629 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002630 AssignmentOps.append(C->assignment_ops().begin(),
2631 C->assignment_ops().end());
2632 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002633 // Emit code for 'single' region along with 'copyprivate' clauses
2634 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2635 Action.Enter(CGF);
2636 OMPPrivateScope SingleScope(CGF);
2637 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2638 CGF.EmitOMPPrivateClause(S, SingleScope);
2639 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002640 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002641 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002642 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002643 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002644 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2645 CopyprivateVars, DestExprs,
2646 SrcExprs, AssignmentOps);
2647 }
2648 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2649 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002650 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002651 CGM.getOpenMPRuntime().emitBarrierCall(
2652 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002653 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002654 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002655}
2656
Alexey Bataev8d690652014-12-04 07:23:53 +00002657void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002658 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2659 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002660 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002662 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002663 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002664}
2665
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002666void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002667 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2668 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002669 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002670 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002671 Expr *Hint = nullptr;
2672 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2673 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002674 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002675 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2676 S.getDirectiveName().getAsString(),
2677 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002678}
2679
Alexey Bataev671605e2015-04-13 05:28:11 +00002680void CodeGenFunction::EmitOMPParallelForDirective(
2681 const OMPParallelForDirective &S) {
2682 // Emit directive as a combined directive that consists of two implicit
2683 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002684 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002685 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002686 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2687 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002688 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002689 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2690 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002691}
2692
Alexander Musmane4e893b2014-09-23 09:33:00 +00002693void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002694 const OMPParallelForSimdDirective &S) {
2695 // Emit directive as a combined directive that consists of two implicit
2696 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002697 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002698 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2699 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002700 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002701 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2702 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002703}
2704
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002705void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002706 const OMPParallelSectionsDirective &S) {
2707 // Emit directive as a combined directive that consists of two implicit
2708 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002709 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2710 CGF.EmitSections(S);
2711 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002712 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2713 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002714}
2715
Alexey Bataev475a7442018-01-12 19:39:11 +00002716void CodeGenFunction::EmitOMPTaskBasedDirective(
2717 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2718 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2719 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002720 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002721 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002722 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002723 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002724 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002725 // Check if the task is final
2726 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2727 // If the condition constant folds and can be elided, try to avoid emitting
2728 // the condition and the dead arm of the if/else.
2729 auto *Cond = Clause->getCondition();
2730 bool CondConstant;
2731 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2732 Data.Final.setInt(CondConstant);
2733 else
2734 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2735 } else {
2736 // By default the task is not final.
2737 Data.Final.setInt(/*IntVal=*/false);
2738 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002739 // Check if the task has 'priority' clause.
2740 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002741 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002742 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002743 Data.Priority.setPointer(EmitScalarConversion(
2744 EmitScalarExpr(Prio), Prio->getType(),
2745 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2746 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002747 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002748 // The first function argument for tasks is a thread id, the second one is a
2749 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002750 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2751 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002752 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002753 auto IRef = C->varlist_begin();
2754 for (auto *IInit : C->private_copies()) {
2755 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2756 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002757 Data.PrivateVars.push_back(*IRef);
2758 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002759 }
2760 ++IRef;
2761 }
2762 }
2763 EmittedAsPrivate.clear();
2764 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002765 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002766 auto IRef = C->varlist_begin();
2767 auto IElemInitRef = C->inits().begin();
2768 for (auto *IInit : C->private_copies()) {
2769 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2770 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002771 Data.FirstprivateVars.push_back(*IRef);
2772 Data.FirstprivateCopies.push_back(IInit);
2773 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002774 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002775 ++IRef;
2776 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002777 }
2778 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002779 // Get list of lastprivate variables (for taskloops).
2780 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2781 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2782 auto IRef = C->varlist_begin();
2783 auto ID = C->destination_exprs().begin();
2784 for (auto *IInit : C->private_copies()) {
2785 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2786 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2787 Data.LastprivateVars.push_back(*IRef);
2788 Data.LastprivateCopies.push_back(IInit);
2789 }
2790 LastprivateDstsOrigs.insert(
2791 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2792 cast<DeclRefExpr>(*IRef)});
2793 ++IRef;
2794 ++ID;
2795 }
2796 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002797 SmallVector<const Expr *, 4> LHSs;
2798 SmallVector<const Expr *, 4> RHSs;
2799 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2800 auto IPriv = C->privates().begin();
2801 auto IRed = C->reduction_ops().begin();
2802 auto ILHS = C->lhs_exprs().begin();
2803 auto IRHS = C->rhs_exprs().begin();
2804 for (const auto *Ref : C->varlists()) {
2805 Data.ReductionVars.emplace_back(Ref);
2806 Data.ReductionCopies.emplace_back(*IPriv);
2807 Data.ReductionOps.emplace_back(*IRed);
2808 LHSs.emplace_back(*ILHS);
2809 RHSs.emplace_back(*IRHS);
2810 std::advance(IPriv, 1);
2811 std::advance(IRed, 1);
2812 std::advance(ILHS, 1);
2813 std::advance(IRHS, 1);
2814 }
2815 }
2816 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2817 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002818 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002819 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2820 for (auto *IRef : C->varlists())
2821 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002822 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2823 CapturedRegion](CodeGenFunction &CGF,
2824 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002825 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002826 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002827 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2828 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002829 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002830 auto *CopyFn = CGF.Builder.CreateLoad(
2831 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2832 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2833 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2834 // Map privates.
2835 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2836 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2837 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002838 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002839 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2840 Address PrivatePtr = CGF.CreateMemTemp(
2841 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2842 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2843 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002844 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002845 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002846 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2847 Address PrivatePtr =
2848 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2849 ".firstpriv.ptr.addr");
2850 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2851 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002852 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002853 for (auto *E : Data.LastprivateVars) {
2854 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2855 Address PrivatePtr =
2856 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2857 ".lastpriv.ptr.addr");
2858 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2859 CallArgs.push_back(PrivatePtr.getPointer());
2860 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002861 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2862 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002863 for (auto &&Pair : LastprivateDstsOrigs) {
2864 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2865 DeclRefExpr DRE(
2866 const_cast<VarDecl *>(OrigVD),
2867 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2868 OrigVD) != nullptr,
2869 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2870 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2871 return CGF.EmitLValue(&DRE).getAddress();
2872 });
2873 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002874 for (auto &&Pair : PrivatePtrs) {
2875 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2876 CGF.getContext().getDeclAlign(Pair.first));
2877 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2878 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002879 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002880 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002881 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002882 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2883 Data.ReductionOps);
2884 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2885 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2886 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2887 RedCG.emitSharedLValue(CGF, Cnt);
2888 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002889 // FIXME: This must removed once the runtime library is fixed.
2890 // Emit required threadprivate variables for
2891 // initilizer/combiner/finalizer.
2892 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2893 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002894 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2895 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2896 Replacement =
2897 Address(CGF.EmitScalarConversion(
2898 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2899 CGF.getContext().getPointerType(
2900 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002901 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002902 Replacement.getAlignment());
2903 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2904 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2905 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002906 }
2907 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002908 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002910 SmallVector<const Expr *, 4> InRedVars;
2911 SmallVector<const Expr *, 4> InRedPrivs;
2912 SmallVector<const Expr *, 4> InRedOps;
2913 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2914 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2915 auto IPriv = C->privates().begin();
2916 auto IRed = C->reduction_ops().begin();
2917 auto ITD = C->taskgroup_descriptors().begin();
2918 for (const auto *Ref : C->varlists()) {
2919 InRedVars.emplace_back(Ref);
2920 InRedPrivs.emplace_back(*IPriv);
2921 InRedOps.emplace_back(*IRed);
2922 TaskgroupDescriptors.emplace_back(*ITD);
2923 std::advance(IPriv, 1);
2924 std::advance(IRed, 1);
2925 std::advance(ITD, 1);
2926 }
2927 }
2928 // Privatize in_reduction items here, because taskgroup descriptors must be
2929 // privatized earlier.
2930 OMPPrivateScope InRedScope(CGF);
2931 if (!InRedVars.empty()) {
2932 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2933 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2934 RedCG.emitSharedLValue(CGF, Cnt);
2935 RedCG.emitAggregateType(CGF, Cnt);
2936 // The taskgroup descriptor variable is always implicit firstprivate and
2937 // privatized already during procoessing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002938 // FIXME: This must removed once the runtime library is fixed.
2939 // Emit required threadprivate variables for
2940 // initilizer/combiner/finalizer.
2941 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2942 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002943 llvm::Value *ReductionsPtr =
2944 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2945 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002946 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2947 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2948 Replacement = Address(
2949 CGF.EmitScalarConversion(
2950 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2951 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002952 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002953 Replacement.getAlignment());
2954 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2955 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2956 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00002957 }
2958 }
2959 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002960
2961 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002962 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002963 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002964 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2965 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2966 Data.NumberOfParts);
2967 OMPLexicalScope Scope(*this, S);
2968 TaskGen(*this, OutlinedFn, Data);
2969}
2970
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002971static ImplicitParamDecl *
2972createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002973 QualType Ty, CapturedDecl *CD,
2974 SourceLocation Loc) {
2975 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2976 ImplicitParamDecl::Other);
2977 auto *OrigRef = DeclRefExpr::Create(
2978 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2979 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2980 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2981 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002982 auto *PrivateRef = DeclRefExpr::Create(
2983 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002984 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002985 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002986 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2987 ImplicitParamDecl::Other);
2988 auto *InitRef = DeclRefExpr::Create(
2989 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2990 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002991 PrivateVD->setInitStyle(VarDecl::CInit);
2992 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2993 InitRef, /*BasePath=*/nullptr,
2994 VK_RValue));
2995 Data.FirstprivateVars.emplace_back(OrigRef);
2996 Data.FirstprivateCopies.emplace_back(PrivateRef);
2997 Data.FirstprivateInits.emplace_back(InitRef);
2998 return OrigVD;
2999}
3000
3001void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3002 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3003 OMPTargetDataInfo &InputInfo) {
3004 // Emit outlined function for task construct.
3005 auto CS = S.getCapturedStmt(OMPD_task);
3006 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3007 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3008 auto *I = CS->getCapturedDecl()->param_begin();
3009 auto *PartId = std::next(I);
3010 auto *TaskT = std::next(I, 4);
3011 OMPTaskDataTy Data;
3012 // The task is not final.
3013 Data.Final.setInt(/*IntVal=*/false);
3014 // Get list of firstprivate variables.
3015 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3016 auto IRef = C->varlist_begin();
3017 auto IElemInitRef = C->inits().begin();
3018 for (auto *IInit : C->private_copies()) {
3019 Data.FirstprivateVars.push_back(*IRef);
3020 Data.FirstprivateCopies.push_back(IInit);
3021 Data.FirstprivateInits.push_back(*IElemInitRef);
3022 ++IRef;
3023 ++IElemInitRef;
3024 }
3025 }
3026 OMPPrivateScope TargetScope(*this);
3027 VarDecl *BPVD = nullptr;
3028 VarDecl *PVD = nullptr;
3029 VarDecl *SVD = nullptr;
3030 if (InputInfo.NumberOfTargetItems > 0) {
3031 auto *CD = CapturedDecl::Create(
3032 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3033 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3034 QualType BaseAndPointersType = getContext().getConstantArrayType(
3035 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3036 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003037 BPVD = createImplicitFirstprivateForType(
3038 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3039 PVD = createImplicitFirstprivateForType(
3040 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003041 QualType SizesType = getContext().getConstantArrayType(
3042 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3043 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003044 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3045 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003046 TargetScope.addPrivate(
3047 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3048 TargetScope.addPrivate(PVD,
3049 [&InputInfo]() { return InputInfo.PointersArray; });
3050 TargetScope.addPrivate(SVD,
3051 [&InputInfo]() { return InputInfo.SizesArray; });
3052 }
3053 (void)TargetScope.Privatize();
3054 // Build list of dependences.
3055 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3056 for (auto *IRef : C->varlists())
3057 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3058 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3059 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3060 // Set proper addresses for generated private copies.
3061 OMPPrivateScope Scope(CGF);
3062 if (!Data.FirstprivateVars.empty()) {
3063 enum { PrivatesParam = 2, CopyFnParam = 3 };
3064 auto *CopyFn = CGF.Builder.CreateLoad(
3065 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3066 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3067 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3068 // Map privates.
3069 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3070 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3071 CallArgs.push_back(PrivatesPtr);
3072 for (auto *E : Data.FirstprivateVars) {
3073 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3074 Address PrivatePtr =
3075 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3076 ".firstpriv.ptr.addr");
3077 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3078 CallArgs.push_back(PrivatePtr.getPointer());
3079 }
3080 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3081 CopyFn, CallArgs);
3082 for (auto &&Pair : PrivatePtrs) {
3083 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3084 CGF.getContext().getDeclAlign(Pair.first));
3085 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3086 }
3087 }
3088 // Privatize all private variables except for in_reduction items.
3089 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003090 if (InputInfo.NumberOfTargetItems > 0) {
3091 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3092 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3093 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3094 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3095 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3096 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3097 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003098
3099 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003100 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003101 BodyGen(CGF);
3102 };
3103 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3104 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3105 Data.NumberOfParts);
3106 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3107 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3108 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3109 SourceLocation());
3110
3111 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3112 SharedsTy, CapturedStruct, &IfCond, Data);
3113}
3114
Alexey Bataev7292c292016-04-25 12:22:29 +00003115void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3116 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003117 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003118 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003119 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003120 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003121 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3122 if (C->getNameModifier() == OMPD_unknown ||
3123 C->getNameModifier() == OMPD_task) {
3124 IfCond = C->getCondition();
3125 break;
3126 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003127 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003128
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003129 OMPTaskDataTy Data;
3130 // Check if we should emit tied or untied task.
3131 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003132 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3133 CGF.EmitStmt(CS->getCapturedStmt());
3134 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003135 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003136 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003137 const OMPTaskDataTy &Data) {
3138 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3139 SharedsTy, CapturedStruct, IfCond,
3140 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003141 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003142 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003143}
3144
Alexey Bataev9f797f32015-02-05 05:57:51 +00003145void CodeGenFunction::EmitOMPTaskyieldDirective(
3146 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003147 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003148}
3149
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003150void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003151 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003152}
3153
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003154void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3155 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003156}
3157
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003158void CodeGenFunction::EmitOMPTaskgroupDirective(
3159 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3161 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003162 if (const Expr *E = S.getReductionRef()) {
3163 SmallVector<const Expr *, 4> LHSs;
3164 SmallVector<const Expr *, 4> RHSs;
3165 OMPTaskDataTy Data;
3166 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3167 auto IPriv = C->privates().begin();
3168 auto IRed = C->reduction_ops().begin();
3169 auto ILHS = C->lhs_exprs().begin();
3170 auto IRHS = C->rhs_exprs().begin();
3171 for (const auto *Ref : C->varlists()) {
3172 Data.ReductionVars.emplace_back(Ref);
3173 Data.ReductionCopies.emplace_back(*IPriv);
3174 Data.ReductionOps.emplace_back(*IRed);
3175 LHSs.emplace_back(*ILHS);
3176 RHSs.emplace_back(*IRHS);
3177 std::advance(IPriv, 1);
3178 std::advance(IRed, 1);
3179 std::advance(ILHS, 1);
3180 std::advance(IRHS, 1);
3181 }
3182 }
3183 llvm::Value *ReductionDesc =
3184 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3185 LHSs, RHSs, Data);
3186 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3187 CGF.EmitVarDecl(*VD);
3188 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3189 /*Volatile=*/false, E->getType());
3190 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003191 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003192 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003193 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003194 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3195}
3196
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003197void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003198 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003199 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003200 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3201 FlushClause->varlist_end());
3202 }
3203 return llvm::None;
3204 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003205}
3206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003207void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3208 const CodeGenLoopTy &CodeGenLoop,
3209 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003210 // Emit the loop iteration variable.
3211 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3212 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3213 EmitVarDecl(*IVDecl);
3214
3215 // Emit the iterations count variable.
3216 // If it is not a variable, Sema decided to calculate iterations count on each
3217 // iteration (e.g., it is foldable into a constant).
3218 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3219 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3220 // Emit calculation of the iterations count.
3221 EmitIgnoredExpr(S.getCalcLastIteration());
3222 }
3223
3224 auto &RT = CGM.getOpenMPRuntime();
3225
Carlo Bertolli962bb802017-01-03 18:24:42 +00003226 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003227 // Check pre-condition.
3228 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003229 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003230 // Skip the entire loop if we don't meet the precondition.
3231 // If the condition constant folds and can be elided, avoid emitting the
3232 // whole loop.
3233 bool CondConstant;
3234 llvm::BasicBlock *ContBlock = nullptr;
3235 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3236 if (!CondConstant)
3237 return;
3238 } else {
3239 auto *ThenBlock = createBasicBlock("omp.precond.then");
3240 ContBlock = createBasicBlock("omp.precond.end");
3241 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3242 getProfileCount(&S));
3243 EmitBlock(ThenBlock);
3244 incrementProfileCounter(&S);
3245 }
3246
Alexey Bataev617db5f2017-12-04 15:38:33 +00003247 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003248 // Emit 'then' code.
3249 {
3250 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003251
3252 LValue LB = EmitOMPHelperVar(
3253 *this, cast<DeclRefExpr>(
3254 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3255 ? S.getCombinedLowerBoundVariable()
3256 : S.getLowerBoundVariable())));
3257 LValue UB = EmitOMPHelperVar(
3258 *this, cast<DeclRefExpr>(
3259 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3260 ? S.getCombinedUpperBoundVariable()
3261 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003262 LValue ST =
3263 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3264 LValue IL =
3265 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3266
3267 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003268 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003269 // Emit implicit barrier to synchronize threads and avoid data races
3270 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003271 // lastprivate variables.
3272 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003273 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3274 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003275 }
3276 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003277 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003278 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3279 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003280 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003281 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003282 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003283 (void)LoopScope.Privatize();
3284
3285 // Detect the distribute schedule kind and chunk.
3286 llvm::Value *Chunk = nullptr;
3287 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3288 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3289 ScheduleKind = C->getDistScheduleKind();
3290 if (const auto *Ch = C->getChunkSize()) {
3291 Chunk = EmitScalarExpr(Ch);
3292 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003293 S.getIterationVariable()->getType(),
3294 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003295 }
3296 }
3297 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3298 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3299
3300 // OpenMP [2.10.8, distribute Construct, Description]
3301 // If dist_schedule is specified, kind must be static. If specified,
3302 // iterations are divided into chunks of size chunk_size, chunks are
3303 // assigned to the teams of the league in a round-robin fashion in the
3304 // order of the team number. When no chunk_size is specified, the
3305 // iteration space is divided into chunks that are approximately equal
3306 // in size, and at most one chunk is distributed to each team of the
3307 // league. The size of the chunks is unspecified in this case.
3308 if (RT.isStaticNonchunked(ScheduleKind,
3309 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003310 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3311 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003312 CGOpenMPRuntime::StaticRTInput StaticInit(
3313 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3314 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003315 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003316 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317 auto LoopExit =
3318 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3319 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003320 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3321 ? S.getCombinedEnsureUpperBound()
3322 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003323 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003324 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3325 ? S.getCombinedInit()
3326 : S.getInit());
3327
3328 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3329 ? S.getCombinedCond()
3330 : S.getCond();
3331
3332 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003333 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003334 // when combined with 'for' (e.g. as in 'distribute parallel for')
3335 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3336 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3337 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3338 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003339 },
3340 [](CodeGenFunction &) {});
3341 EmitBlock(LoopExit.getBlock());
3342 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003343 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003344 } else {
3345 // Emit the outer loop, which requests its work chunk [LB..UB] from
3346 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003347 const OMPLoopArguments LoopArguments = {
3348 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3349 Chunk};
3350 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3351 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003352 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003353 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3354 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3355 return CGF.Builder.CreateIsNotNull(
3356 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3357 });
3358 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003359 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3360 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3361 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3362 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3363 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3364 isOpenMPSimdDirective(S.getDirectiveKind())) {
3365 ReductionKind = OMPD_parallel_for_simd;
3366 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3367 ReductionKind = OMPD_parallel_for;
3368 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3369 ReductionKind = OMPD_simd;
3370 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3371 S.hasClausesOfKind<OMPReductionClause>()) {
3372 llvm_unreachable(
3373 "No reduction clauses is allowed in distribute directive.");
3374 }
3375 EmitOMPReductionClauseFinal(S, ReductionKind);
3376 // Emit post-update of the reduction variables if IsLastIter != 0.
3377 emitPostUpdateForReductionClause(
3378 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3379 return CGF.Builder.CreateIsNotNull(
3380 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3381 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003382 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003383 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003384 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003385 EmitOMPLastprivateClauseFinal(
3386 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003387 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3388 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003389 }
3390
3391 // We're now done with the loop, so jump to the continuation block.
3392 if (ContBlock) {
3393 EmitBranch(ContBlock);
3394 EmitBlock(ContBlock, true);
3395 }
3396 }
3397}
3398
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003399void CodeGenFunction::EmitOMPDistributeDirective(
3400 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003401 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003402
3403 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003404 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003405 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003406 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003407}
3408
Alexey Bataev5f600d62015-09-29 03:48:57 +00003409static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3410 const CapturedStmt *S) {
3411 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3412 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3413 CGF.CapturedStmtInfo = &CapStmtInfo;
3414 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3415 Fn->addFnAttr(llvm::Attribute::NoInline);
3416 return Fn;
3417}
3418
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003419void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003420 if (S.hasClausesOfKind<OMPDependClause>()) {
3421 assert(!S.getAssociatedStmt() &&
3422 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003423 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3424 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003425 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003426 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003427 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003428 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3429 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003430 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003431 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003432 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3433 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3434 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003435 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3436 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003437 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003438 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003439 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003440 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003441 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003442 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003443 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003444}
3445
Alexey Bataevb57056f2015-01-22 06:17:56 +00003446static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003447 QualType SrcType, QualType DestType,
3448 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003449 assert(CGF.hasScalarEvaluationKind(DestType) &&
3450 "DestType must have scalar evaluation kind.");
3451 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3452 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003453 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3454 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003455 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003456 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003457}
3458
3459static CodeGenFunction::ComplexPairTy
3460convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003461 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003462 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3463 "DestType must have complex evaluation kind.");
3464 CodeGenFunction::ComplexPairTy ComplexVal;
3465 if (Val.isScalar()) {
3466 // Convert the input element to the element type of the complex.
3467 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003468 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3469 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003470 ComplexVal = CodeGenFunction::ComplexPairTy(
3471 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3472 } else {
3473 assert(Val.isComplex() && "Must be a scalar or complex.");
3474 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3475 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3476 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003477 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003478 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003479 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003480 }
3481 return ComplexVal;
3482}
3483
Alexey Bataev5e018f92015-04-23 06:35:10 +00003484static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3485 LValue LVal, RValue RVal) {
3486 if (LVal.isGlobalReg()) {
3487 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3488 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003489 CGF.EmitAtomicStore(RVal, LVal,
3490 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3491 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003492 LVal.isVolatile(), /*IsInit=*/false);
3493 }
3494}
3495
Alexey Bataev8524d152016-01-21 12:35:58 +00003496void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3497 QualType RValTy, SourceLocation Loc) {
3498 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003499 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003500 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3501 *this, RVal, RValTy, LVal.getType(), Loc)),
3502 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003503 break;
3504 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003505 EmitStoreOfComplex(
3506 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003507 /*isInit=*/false);
3508 break;
3509 case TEK_Aggregate:
3510 llvm_unreachable("Must be a scalar or complex.");
3511 }
3512}
3513
Alexey Bataevb57056f2015-01-22 06:17:56 +00003514static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3515 const Expr *X, const Expr *V,
3516 SourceLocation Loc) {
3517 // v = x;
3518 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3519 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3520 LValue XLValue = CGF.EmitLValue(X);
3521 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003522 RValue Res = XLValue.isGlobalReg()
3523 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003524 : CGF.EmitAtomicLoad(
3525 XLValue, Loc,
3526 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3527 : llvm::AtomicOrdering::Monotonic,
3528 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003529 // OpenMP, 2.12.6, atomic Construct
3530 // Any atomic construct with a seq_cst clause forces the atomically
3531 // performed operation to include an implicit flush operation without a
3532 // list.
3533 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003534 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003535 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003536}
3537
Alexey Bataevb8329262015-02-27 06:33:30 +00003538static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3539 const Expr *X, const Expr *E,
3540 SourceLocation Loc) {
3541 // x = expr;
3542 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003543 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003544 // OpenMP, 2.12.6, atomic Construct
3545 // Any atomic construct with a seq_cst clause forces the atomically
3546 // performed operation to include an implicit flush operation without a
3547 // list.
3548 if (IsSeqCst)
3549 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3550}
3551
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003552static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3553 RValue Update,
3554 BinaryOperatorKind BO,
3555 llvm::AtomicOrdering AO,
3556 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003557 auto &Context = CGF.CGM.getContext();
3558 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003559 // expression is simple and atomic is allowed for the given type for the
3560 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003561 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003562 !Update.getScalarVal()->getType()->isIntegerTy() ||
3563 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3564 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003565 X.getAddress().getElementType())) ||
3566 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003567 !Context.getTargetInfo().hasBuiltinAtomic(
3568 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003569 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003570
3571 llvm::AtomicRMWInst::BinOp RMWOp;
3572 switch (BO) {
3573 case BO_Add:
3574 RMWOp = llvm::AtomicRMWInst::Add;
3575 break;
3576 case BO_Sub:
3577 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003578 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003579 RMWOp = llvm::AtomicRMWInst::Sub;
3580 break;
3581 case BO_And:
3582 RMWOp = llvm::AtomicRMWInst::And;
3583 break;
3584 case BO_Or:
3585 RMWOp = llvm::AtomicRMWInst::Or;
3586 break;
3587 case BO_Xor:
3588 RMWOp = llvm::AtomicRMWInst::Xor;
3589 break;
3590 case BO_LT:
3591 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3592 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3593 : llvm::AtomicRMWInst::Max)
3594 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3595 : llvm::AtomicRMWInst::UMax);
3596 break;
3597 case BO_GT:
3598 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3599 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3600 : llvm::AtomicRMWInst::Min)
3601 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3602 : llvm::AtomicRMWInst::UMin);
3603 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003604 case BO_Assign:
3605 RMWOp = llvm::AtomicRMWInst::Xchg;
3606 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003607 case BO_Mul:
3608 case BO_Div:
3609 case BO_Rem:
3610 case BO_Shl:
3611 case BO_Shr:
3612 case BO_LAnd:
3613 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003614 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003615 case BO_PtrMemD:
3616 case BO_PtrMemI:
3617 case BO_LE:
3618 case BO_GE:
3619 case BO_EQ:
3620 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003621 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003622 case BO_AddAssign:
3623 case BO_SubAssign:
3624 case BO_AndAssign:
3625 case BO_OrAssign:
3626 case BO_XorAssign:
3627 case BO_MulAssign:
3628 case BO_DivAssign:
3629 case BO_RemAssign:
3630 case BO_ShlAssign:
3631 case BO_ShrAssign:
3632 case BO_Comma:
3633 llvm_unreachable("Unsupported atomic update operation");
3634 }
3635 auto *UpdateVal = Update.getScalarVal();
3636 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3637 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003638 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003639 X.getType()->hasSignedIntegerRepresentation());
3640 }
John McCall7f416cc2015-09-08 08:05:57 +00003641 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003642 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003643}
3644
Alexey Bataev5e018f92015-04-23 06:35:10 +00003645std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003646 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3647 llvm::AtomicOrdering AO, SourceLocation Loc,
3648 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3649 // Update expressions are allowed to have the following forms:
3650 // x binop= expr; -> xrval + expr;
3651 // x++, ++x -> xrval + 1;
3652 // x--, --x -> xrval - 1;
3653 // x = x binop expr; -> xrval binop expr
3654 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003655 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3656 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003657 if (X.isGlobalReg()) {
3658 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3659 // 'xrval'.
3660 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3661 } else {
3662 // Perform compare-and-swap procedure.
3663 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003664 }
3665 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003666 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003667}
3668
3669static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3670 const Expr *X, const Expr *E,
3671 const Expr *UE, bool IsXLHSInRHSPart,
3672 SourceLocation Loc) {
3673 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3674 "Update expr in 'atomic update' must be a binary operator.");
3675 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3676 // Update expressions are allowed to have the following forms:
3677 // x binop= expr; -> xrval + expr;
3678 // x++, ++x -> xrval + 1;
3679 // x--, --x -> xrval - 1;
3680 // x = x binop expr; -> xrval binop expr
3681 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003682 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003683 LValue XLValue = CGF.EmitLValue(X);
3684 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003685 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3686 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003687 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3688 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3689 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3690 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3691 auto Gen =
3692 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3693 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3694 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3695 return CGF.EmitAnyExpr(UE);
3696 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003697 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3698 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3699 // OpenMP, 2.12.6, atomic Construct
3700 // Any atomic construct with a seq_cst clause forces the atomically
3701 // performed operation to include an implicit flush operation without a
3702 // list.
3703 if (IsSeqCst)
3704 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3705}
3706
3707static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003708 QualType SourceType, QualType ResType,
3709 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003710 switch (CGF.getEvaluationKind(ResType)) {
3711 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003712 return RValue::get(
3713 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003714 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003715 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003716 return RValue::getComplex(Res.first, Res.second);
3717 }
3718 case TEK_Aggregate:
3719 break;
3720 }
3721 llvm_unreachable("Must be a scalar or complex.");
3722}
3723
3724static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3725 bool IsPostfixUpdate, const Expr *V,
3726 const Expr *X, const Expr *E,
3727 const Expr *UE, bool IsXLHSInRHSPart,
3728 SourceLocation Loc) {
3729 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3730 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3731 RValue NewVVal;
3732 LValue VLValue = CGF.EmitLValue(V);
3733 LValue XLValue = CGF.EmitLValue(X);
3734 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003735 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3736 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003737 QualType NewVValType;
3738 if (UE) {
3739 // 'x' is updated with some additional value.
3740 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3741 "Update expr in 'atomic capture' must be a binary operator.");
3742 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3743 // Update expressions are allowed to have the following forms:
3744 // x binop= expr; -> xrval + expr;
3745 // x++, ++x -> xrval + 1;
3746 // x--, --x -> xrval - 1;
3747 // x = x binop expr; -> xrval binop expr
3748 // x = expr Op x; - > expr binop xrval;
3749 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3750 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3751 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3752 NewVValType = XRValExpr->getType();
3753 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3754 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003755 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003756 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3757 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3758 RValue Res = CGF.EmitAnyExpr(UE);
3759 NewVVal = IsPostfixUpdate ? XRValue : Res;
3760 return Res;
3761 };
3762 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3763 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3764 if (Res.first) {
3765 // 'atomicrmw' instruction was generated.
3766 if (IsPostfixUpdate) {
3767 // Use old value from 'atomicrmw'.
3768 NewVVal = Res.second;
3769 } else {
3770 // 'atomicrmw' does not provide new value, so evaluate it using old
3771 // value of 'x'.
3772 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3773 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3774 NewVVal = CGF.EmitAnyExpr(UE);
3775 }
3776 }
3777 } else {
3778 // 'x' is simply rewritten with some 'expr'.
3779 NewVValType = X->getType().getNonReferenceType();
3780 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003781 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003782 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003783 NewVVal = XRValue;
3784 return ExprRValue;
3785 };
3786 // Try to perform atomicrmw xchg, otherwise simple exchange.
3787 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3788 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3789 Loc, Gen);
3790 if (Res.first) {
3791 // 'atomicrmw' instruction was generated.
3792 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3793 }
3794 }
3795 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003796 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003797 // 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
Alexey Bataevb57056f2015-01-22 06:17:56 +00003805static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003806 bool IsSeqCst, bool IsPostfixUpdate,
3807 const Expr *X, const Expr *V, const Expr *E,
3808 const Expr *UE, bool IsXLHSInRHSPart,
3809 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003810 switch (Kind) {
3811 case OMPC_read:
3812 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3813 break;
3814 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003815 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3816 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003817 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003818 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003819 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3820 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003821 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003822 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3823 IsXLHSInRHSPart, Loc);
3824 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003825 case OMPC_if:
3826 case OMPC_final:
3827 case OMPC_num_threads:
3828 case OMPC_private:
3829 case OMPC_firstprivate:
3830 case OMPC_lastprivate:
3831 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003832 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003833 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003834 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003835 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003836 case OMPC_collapse:
3837 case OMPC_default:
3838 case OMPC_seq_cst:
3839 case OMPC_shared:
3840 case OMPC_linear:
3841 case OMPC_aligned:
3842 case OMPC_copyin:
3843 case OMPC_copyprivate:
3844 case OMPC_flush:
3845 case OMPC_proc_bind:
3846 case OMPC_schedule:
3847 case OMPC_ordered:
3848 case OMPC_nowait:
3849 case OMPC_untied:
3850 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003851 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003852 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003853 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003854 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003855 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003856 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003857 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003858 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003859 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003860 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003861 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003862 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003863 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003864 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003865 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003866 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003867 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003868 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003869 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003870 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003871 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3872 }
3873}
3874
3875void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003876 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003877 OpenMPClauseKind Kind = OMPC_unknown;
3878 for (auto *C : S.clauses()) {
3879 // Find first clause (skip seq_cst clause, if it is first).
3880 if (C->getClauseKind() != OMPC_seq_cst) {
3881 Kind = C->getClauseKind();
3882 break;
3883 }
3884 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003885
Alexey Bataev475a7442018-01-12 19:39:11 +00003886 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003887 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003888 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003889 }
3890 // Processing for statements under 'atomic capture'.
3891 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3892 for (const auto *C : Compound->body()) {
3893 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3894 enterFullExpression(EWC);
3895 }
3896 }
3897 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003898
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003899 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3900 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003901 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003902 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3903 S.getV(), S.getExpr(), S.getUpdateExpr(),
3904 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003905 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003906 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003907 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003908}
3909
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003910static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3911 const OMPExecutableDirective &S,
3912 const RegionCodeGenTy &CodeGen) {
3913 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3914 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003915
Samuel Antaoee8fb302016-01-06 13:42:12 +00003916 llvm::Function *Fn = nullptr;
3917 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003918
Samuel Antaobed3c462015-10-02 16:14:20 +00003919 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003920 // Check for the at most one if clause associated with the target region.
3921 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3922 if (C->getNameModifier() == OMPD_unknown ||
3923 C->getNameModifier() == OMPD_target) {
3924 IfCond = C->getCondition();
3925 break;
3926 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003927 }
3928
3929 // Check if we have any device clause associated with the directive.
3930 const Expr *Device = nullptr;
3931 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3932 Device = C->getDevice();
3933 }
3934
Samuel Antaoee8fb302016-01-06 13:42:12 +00003935 // Check if we have an if clause whose conditional always evaluates to false
3936 // or if we do not have any targets specified. If so the target region is not
3937 // an offload entry point.
3938 bool IsOffloadEntry = true;
3939 if (IfCond) {
3940 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003941 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 IsOffloadEntry = false;
3943 }
3944 if (CGM.getLangOpts().OMPTargetTriples.empty())
3945 IsOffloadEntry = false;
3946
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003947 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948 StringRef ParentName;
3949 // In case we have Ctors/Dtors we use the complete type variant to produce
3950 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003951 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003952 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003953 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003954 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3955 else
3956 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003957 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003958
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003959 // Emit target region as a standalone region.
3960 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3961 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003962 OMPLexicalScope Scope(CGF, S, OMPD_task);
3963 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003964}
3965
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003966static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3967 PrePostActionTy &Action) {
3968 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3969 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3970 CGF.EmitOMPPrivateClause(S, PrivateScope);
3971 (void)PrivateScope.Privatize();
3972
3973 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003974 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003975}
3976
3977void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3978 StringRef ParentName,
3979 const OMPTargetDirective &S) {
3980 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3981 emitTargetRegion(CGF, S, Action);
3982 };
3983 llvm::Function *Fn;
3984 llvm::Constant *Addr;
3985 // Emit target region as a standalone region.
3986 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3987 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3988 assert(Fn && Addr && "Target device function emission failed.");
3989}
3990
3991void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3992 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3993 emitTargetRegion(CGF, S, Action);
3994 };
3995 emitCommonOMPTargetDirective(*this, S, CodeGen);
3996}
3997
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003998static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3999 const OMPExecutableDirective &S,
4000 OpenMPDirectiveKind InnermostKind,
4001 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004002 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4003 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4004 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004005
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004006 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4007 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004008 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004009 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4010 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004011
Carlo Bertollic6872252016-04-04 15:55:02 +00004012 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4013 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004014 }
4015
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004016 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004017 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4018 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004019 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4020 CapturedVars);
4021}
4022
4023void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004024 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004025 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004026 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004027 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4028 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004030 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004031 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004032 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004033 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004034 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004035 emitPostUpdateForReductionClause(
4036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004037}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004038
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004039static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4040 const OMPTargetTeamsDirective &S) {
4041 auto *CS = S.getCapturedStmt(OMPD_teams);
4042 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004043 // Emit teams region as a standalone region.
4044 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4045 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4046 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4047 CGF.EmitOMPPrivateClause(S, PrivateScope);
4048 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4049 (void)PrivateScope.Privatize();
4050 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004051 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004052 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004053 };
4054 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004055 emitPostUpdateForReductionClause(
4056 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004057}
4058
4059void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4060 CodeGenModule &CGM, StringRef ParentName,
4061 const OMPTargetTeamsDirective &S) {
4062 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4063 emitTargetTeamsRegion(CGF, Action, S);
4064 };
4065 llvm::Function *Fn;
4066 llvm::Constant *Addr;
4067 // Emit target region as a standalone region.
4068 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4069 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4070 assert(Fn && Addr && "Target device function emission failed.");
4071}
4072
4073void CodeGenFunction::EmitOMPTargetTeamsDirective(
4074 const OMPTargetTeamsDirective &S) {
4075 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4076 emitTargetTeamsRegion(CGF, Action, S);
4077 };
4078 emitCommonOMPTargetDirective(*this, S, CodeGen);
4079}
4080
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004081static void
4082emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4083 const OMPTargetTeamsDistributeDirective &S) {
4084 Action.Enter(CGF);
4085 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4086 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4087 };
4088
4089 // Emit teams region as a standalone region.
4090 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4091 PrePostActionTy &) {
4092 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4093 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4094 (void)PrivateScope.Privatize();
4095 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4096 CodeGenDistribute);
4097 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4098 };
4099 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4100 emitPostUpdateForReductionClause(CGF, S,
4101 [](CodeGenFunction &) { return nullptr; });
4102}
4103
4104void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4105 CodeGenModule &CGM, StringRef ParentName,
4106 const OMPTargetTeamsDistributeDirective &S) {
4107 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4108 emitTargetTeamsDistributeRegion(CGF, Action, S);
4109 };
4110 llvm::Function *Fn;
4111 llvm::Constant *Addr;
4112 // Emit target region as a standalone region.
4113 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4114 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4115 assert(Fn && Addr && "Target device function emission failed.");
4116}
4117
4118void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4119 const OMPTargetTeamsDistributeDirective &S) {
4120 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4121 emitTargetTeamsDistributeRegion(CGF, Action, S);
4122 };
4123 emitCommonOMPTargetDirective(*this, S, CodeGen);
4124}
4125
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004126static void emitTargetTeamsDistributeSimdRegion(
4127 CodeGenFunction &CGF, PrePostActionTy &Action,
4128 const OMPTargetTeamsDistributeSimdDirective &S) {
4129 Action.Enter(CGF);
4130 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4131 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4132 };
4133
4134 // Emit teams region as a standalone region.
4135 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4136 PrePostActionTy &) {
4137 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4138 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4139 (void)PrivateScope.Privatize();
4140 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4141 CodeGenDistribute);
4142 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4143 };
4144 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4145 emitPostUpdateForReductionClause(CGF, S,
4146 [](CodeGenFunction &) { return nullptr; });
4147}
4148
4149void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4150 CodeGenModule &CGM, StringRef ParentName,
4151 const OMPTargetTeamsDistributeSimdDirective &S) {
4152 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4153 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4154 };
4155 llvm::Function *Fn;
4156 llvm::Constant *Addr;
4157 // Emit target region as a standalone region.
4158 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4159 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4160 assert(Fn && Addr && "Target device function emission failed.");
4161}
4162
4163void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4164 const OMPTargetTeamsDistributeSimdDirective &S) {
4165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4166 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4167 };
4168 emitCommonOMPTargetDirective(*this, S, CodeGen);
4169}
4170
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004171void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4172 const OMPTeamsDistributeDirective &S) {
4173
4174 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4175 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4176 };
4177
4178 // Emit teams region as a standalone region.
4179 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4180 PrePostActionTy &) {
4181 OMPPrivateScope PrivateScope(CGF);
4182 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4183 (void)PrivateScope.Privatize();
4184 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4185 CodeGenDistribute);
4186 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4187 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004188 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004189 emitPostUpdateForReductionClause(*this, S,
4190 [](CodeGenFunction &) { return nullptr; });
4191}
4192
Alexey Bataev999277a2017-12-06 14:31:09 +00004193void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4194 const OMPTeamsDistributeSimdDirective &S) {
4195 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4196 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4197 };
4198
4199 // Emit teams region as a standalone region.
4200 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4201 PrePostActionTy &) {
4202 OMPPrivateScope PrivateScope(CGF);
4203 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4204 (void)PrivateScope.Privatize();
4205 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4206 CodeGenDistribute);
4207 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4208 };
4209 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4210 emitPostUpdateForReductionClause(*this, S,
4211 [](CodeGenFunction &) { return nullptr; });
4212}
4213
Carlo Bertolli62fae152017-11-20 20:46:39 +00004214void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4215 const OMPTeamsDistributeParallelForDirective &S) {
4216 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4217 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4218 S.getDistInc());
4219 };
4220
4221 // Emit teams region as a standalone region.
4222 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4223 PrePostActionTy &) {
4224 OMPPrivateScope PrivateScope(CGF);
4225 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4226 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004227 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4228 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004229 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4230 };
4231 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4232 emitPostUpdateForReductionClause(*this, S,
4233 [](CodeGenFunction &) { return nullptr; });
4234}
4235
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004236void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4237 const OMPTeamsDistributeParallelForSimdDirective &S) {
4238 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4239 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4240 S.getDistInc());
4241 };
4242
4243 // Emit teams region as a standalone region.
4244 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4245 PrePostActionTy &) {
4246 OMPPrivateScope PrivateScope(CGF);
4247 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4248 (void)PrivateScope.Privatize();
4249 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4250 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4251 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4252 };
4253 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4254 emitPostUpdateForReductionClause(*this, S,
4255 [](CodeGenFunction &) { return nullptr; });
4256}
4257
Carlo Bertolli52978c32018-01-03 21:12:44 +00004258static void emitTargetTeamsDistributeParallelForRegion(
4259 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4260 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004261 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004262 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4263 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4264 S.getDistInc());
4265 };
4266
4267 // Emit teams region as a standalone region.
4268 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4269 PrePostActionTy &) {
4270 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4271 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4272 (void)PrivateScope.Privatize();
4273 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4274 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4275 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4276 };
4277
4278 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4279 CodeGenTeams);
4280 emitPostUpdateForReductionClause(CGF, S,
4281 [](CodeGenFunction &) { return nullptr; });
4282}
4283
4284void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4285 CodeGenModule &CGM, StringRef ParentName,
4286 const OMPTargetTeamsDistributeParallelForDirective &S) {
4287 // Emit SPMD target teams distribute parallel for region as a standalone
4288 // region.
4289 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4290 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4291 };
4292 llvm::Function *Fn;
4293 llvm::Constant *Addr;
4294 // Emit target region as a standalone region.
4295 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4296 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4297 assert(Fn && Addr && "Target device function emission failed.");
4298}
4299
4300void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4301 const OMPTargetTeamsDistributeParallelForDirective &S) {
4302 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4303 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4304 };
4305 emitCommonOMPTargetDirective(*this, S, CodeGen);
4306}
4307
Alexey Bataev647dd842018-01-15 20:59:40 +00004308static void emitTargetTeamsDistributeParallelForSimdRegion(
4309 CodeGenFunction &CGF,
4310 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4311 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004312 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004313 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4314 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4315 S.getDistInc());
4316 };
4317
4318 // Emit teams region as a standalone region.
4319 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4320 PrePostActionTy &) {
4321 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4322 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4323 (void)PrivateScope.Privatize();
4324 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4325 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4326 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4327 };
4328
4329 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4330 CodeGenTeams);
4331 emitPostUpdateForReductionClause(CGF, S,
4332 [](CodeGenFunction &) { return nullptr; });
4333}
4334
4335void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4336 CodeGenModule &CGM, StringRef ParentName,
4337 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4338 // Emit SPMD target teams distribute parallel for simd region as a standalone
4339 // region.
4340 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4341 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4342 };
4343 llvm::Function *Fn;
4344 llvm::Constant *Addr;
4345 // Emit target region as a standalone region.
4346 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4347 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4348 assert(Fn && Addr && "Target device function emission failed.");
4349}
4350
4351void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4352 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4353 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4354 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4355 };
4356 emitCommonOMPTargetDirective(*this, S, CodeGen);
4357}
4358
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004359void CodeGenFunction::EmitOMPCancellationPointDirective(
4360 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004361 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4362 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004363}
4364
Alexey Bataev80909872015-07-02 11:25:17 +00004365void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004366 const Expr *IfCond = nullptr;
4367 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4368 if (C->getNameModifier() == OMPD_unknown ||
4369 C->getNameModifier() == OMPD_cancel) {
4370 IfCond = C->getCondition();
4371 break;
4372 }
4373 }
4374 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004375 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004376}
4377
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004378CodeGenFunction::JumpDest
4379CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004380 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4381 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004382 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004383 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004384 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4385 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004386 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004387 Kind == OMPD_teams_distribute_parallel_for ||
4388 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004389 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004390}
Michael Wong65f367f2015-07-21 13:44:28 +00004391
Samuel Antaocc10b852016-07-28 14:23:26 +00004392void CodeGenFunction::EmitOMPUseDevicePtrClause(
4393 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4394 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4395 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4396 auto OrigVarIt = C.varlist_begin();
4397 auto InitIt = C.inits().begin();
4398 for (auto PvtVarIt : C.private_copies()) {
4399 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4400 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4401 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4402
4403 // In order to identify the right initializer we need to match the
4404 // declaration used by the mapping logic. In some cases we may get
4405 // OMPCapturedExprDecl that refers to the original declaration.
4406 const ValueDecl *MatchingVD = OrigVD;
4407 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4408 // OMPCapturedExprDecl are used to privative fields of the current
4409 // structure.
4410 auto *ME = cast<MemberExpr>(OED->getInit());
4411 assert(isa<CXXThisExpr>(ME->getBase()) &&
4412 "Base should be the current struct!");
4413 MatchingVD = ME->getMemberDecl();
4414 }
4415
4416 // If we don't have information about the current list item, move on to
4417 // the next one.
4418 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4419 if (InitAddrIt == CaptureDeviceAddrMap.end())
4420 continue;
4421
4422 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4423 // Initialize the temporary initialization variable with the address we
4424 // get from the runtime library. We have to cast the source address
4425 // because it is always a void *. References are materialized in the
4426 // privatization scope, so the initialization here disregards the fact
4427 // the original variable is a reference.
4428 QualType AddrQTy =
4429 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4430 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4431 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4432 setAddrOfLocalVar(InitVD, InitAddr);
4433
4434 // Emit private declaration, it will be initialized by the value we
4435 // declaration we just added to the local declarations map.
4436 EmitDecl(*PvtVD);
4437
4438 // The initialization variables reached its purpose in the emission
4439 // ofthe previous declaration, so we don't need it anymore.
4440 LocalDeclMap.erase(InitVD);
4441
4442 // Return the address of the private variable.
4443 return GetAddrOfLocalVar(PvtVD);
4444 });
4445 assert(IsRegistered && "firstprivate var already registered as private");
4446 // Silence the warning about unused variable.
4447 (void)IsRegistered;
4448
4449 ++OrigVarIt;
4450 ++InitIt;
4451 }
4452}
4453
Michael Wong65f367f2015-07-21 13:44:28 +00004454// Generate the instructions for '#pragma omp target data' directive.
4455void CodeGenFunction::EmitOMPTargetDataDirective(
4456 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004457 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4458
4459 // Create a pre/post action to signal the privatization of the device pointer.
4460 // This action can be replaced by the OpenMP runtime code generation to
4461 // deactivate privatization.
4462 bool PrivatizeDevicePointers = false;
4463 class DevicePointerPrivActionTy : public PrePostActionTy {
4464 bool &PrivatizeDevicePointers;
4465
4466 public:
4467 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4468 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4469 void Enter(CodeGenFunction &CGF) override {
4470 PrivatizeDevicePointers = true;
4471 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004472 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004473 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4474
4475 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004476 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004477 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004478 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004479 };
4480
4481 // Codegen that selects wheather to generate the privatization code or not.
4482 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4483 &InnermostCodeGen](CodeGenFunction &CGF,
4484 PrePostActionTy &Action) {
4485 RegionCodeGenTy RCG(InnermostCodeGen);
4486 PrivatizeDevicePointers = false;
4487
4488 // Call the pre-action to change the status of PrivatizeDevicePointers if
4489 // needed.
4490 Action.Enter(CGF);
4491
4492 if (PrivatizeDevicePointers) {
4493 OMPPrivateScope PrivateScope(CGF);
4494 // Emit all instances of the use_device_ptr clause.
4495 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4496 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4497 Info.CaptureDeviceAddrMap);
4498 (void)PrivateScope.Privatize();
4499 RCG(CGF);
4500 } else
4501 RCG(CGF);
4502 };
4503
4504 // Forward the provided action to the privatization codegen.
4505 RegionCodeGenTy PrivRCG(PrivCodeGen);
4506 PrivRCG.setAction(Action);
4507
4508 // Notwithstanding the body of the region is emitted as inlined directive,
4509 // we don't use an inline scope as changes in the references inside the
4510 // region are expected to be visible outside, so we do not privative them.
4511 OMPLexicalScope Scope(CGF, S);
4512 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4513 PrivRCG);
4514 };
4515
4516 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004517
4518 // If we don't have target devices, don't bother emitting the data mapping
4519 // code.
4520 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004521 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004522 return;
4523 }
4524
4525 // Check if we have any if clause associated with the directive.
4526 const Expr *IfCond = nullptr;
4527 if (auto *C = S.getSingleClause<OMPIfClause>())
4528 IfCond = C->getCondition();
4529
4530 // Check if we have any device clause associated with the directive.
4531 const Expr *Device = nullptr;
4532 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4533 Device = C->getDevice();
4534
Samuel Antaocc10b852016-07-28 14:23:26 +00004535 // Set the action to signal privatization of device pointers.
4536 RCG.setAction(PrivAction);
4537
4538 // Emit region code.
4539 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4540 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004541}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004542
Samuel Antaodf67fc42016-01-19 19:15:56 +00004543void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4544 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004545 // If we don't have target devices, don't bother emitting the data mapping
4546 // code.
4547 if (CGM.getLangOpts().OMPTargetTriples.empty())
4548 return;
4549
4550 // Check if we have any if clause associated with the directive.
4551 const Expr *IfCond = nullptr;
4552 if (auto *C = S.getSingleClause<OMPIfClause>())
4553 IfCond = C->getCondition();
4554
4555 // Check if we have any device clause associated with the directive.
4556 const Expr *Device = nullptr;
4557 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4558 Device = C->getDevice();
4559
Alexey Bataev475a7442018-01-12 19:39:11 +00004560 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004561 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004562}
4563
Samuel Antao72590762016-01-19 20:04:50 +00004564void CodeGenFunction::EmitOMPTargetExitDataDirective(
4565 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004566 // If we don't have target devices, don't bother emitting the data mapping
4567 // code.
4568 if (CGM.getLangOpts().OMPTargetTriples.empty())
4569 return;
4570
4571 // Check if we have any if clause associated with the directive.
4572 const Expr *IfCond = nullptr;
4573 if (auto *C = S.getSingleClause<OMPIfClause>())
4574 IfCond = C->getCondition();
4575
4576 // Check if we have any device clause associated with the directive.
4577 const Expr *Device = nullptr;
4578 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4579 Device = C->getDevice();
4580
Alexey Bataev475a7442018-01-12 19:39:11 +00004581 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004582 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004583}
4584
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004585static void emitTargetParallelRegion(CodeGenFunction &CGF,
4586 const OMPTargetParallelDirective &S,
4587 PrePostActionTy &Action) {
4588 // Get the captured statement associated with the 'parallel' region.
4589 auto *CS = S.getCapturedStmt(OMPD_parallel);
4590 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004591 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4592 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4593 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4594 CGF.EmitOMPPrivateClause(S, PrivateScope);
4595 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4596 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004597 // TODO: Add support for clauses.
4598 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004599 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004600 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004601 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4602 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004603 emitPostUpdateForReductionClause(
4604 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004605}
4606
4607void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4608 CodeGenModule &CGM, StringRef ParentName,
4609 const OMPTargetParallelDirective &S) {
4610 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4611 emitTargetParallelRegion(CGF, S, Action);
4612 };
4613 llvm::Function *Fn;
4614 llvm::Constant *Addr;
4615 // Emit target region as a standalone region.
4616 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4617 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4618 assert(Fn && Addr && "Target device function emission failed.");
4619}
4620
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004621void CodeGenFunction::EmitOMPTargetParallelDirective(
4622 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004623 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4624 emitTargetParallelRegion(CGF, S, Action);
4625 };
4626 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004627}
4628
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004629static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4630 const OMPTargetParallelForDirective &S,
4631 PrePostActionTy &Action) {
4632 Action.Enter(CGF);
4633 // Emit directive as a combined directive that consists of two implicit
4634 // directives: 'parallel' with 'for' directive.
4635 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004636 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4637 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004638 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4639 emitDispatchForLoopBounds);
4640 };
4641 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4642 emitEmptyBoundParameters);
4643}
4644
4645void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4646 CodeGenModule &CGM, StringRef ParentName,
4647 const OMPTargetParallelForDirective &S) {
4648 // Emit SPMD target parallel for region as a standalone region.
4649 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4650 emitTargetParallelForRegion(CGF, S, Action);
4651 };
4652 llvm::Function *Fn;
4653 llvm::Constant *Addr;
4654 // Emit target region as a standalone region.
4655 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4656 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4657 assert(Fn && Addr && "Target device function emission failed.");
4658}
4659
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004660void CodeGenFunction::EmitOMPTargetParallelForDirective(
4661 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004662 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4663 emitTargetParallelForRegion(CGF, S, Action);
4664 };
4665 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004666}
4667
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004668static void
4669emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4670 const OMPTargetParallelForSimdDirective &S,
4671 PrePostActionTy &Action) {
4672 Action.Enter(CGF);
4673 // Emit directive as a combined directive that consists of two implicit
4674 // directives: 'parallel' with 'for' directive.
4675 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4676 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4677 emitDispatchForLoopBounds);
4678 };
4679 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4680 emitEmptyBoundParameters);
4681}
4682
4683void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4684 CodeGenModule &CGM, StringRef ParentName,
4685 const OMPTargetParallelForSimdDirective &S) {
4686 // Emit SPMD target parallel for region as a standalone region.
4687 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4688 emitTargetParallelForSimdRegion(CGF, S, Action);
4689 };
4690 llvm::Function *Fn;
4691 llvm::Constant *Addr;
4692 // Emit target region as a standalone region.
4693 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4694 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4695 assert(Fn && Addr && "Target device function emission failed.");
4696}
4697
4698void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4699 const OMPTargetParallelForSimdDirective &S) {
4700 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4701 emitTargetParallelForSimdRegion(CGF, S, Action);
4702 };
4703 emitCommonOMPTargetDirective(*this, S, CodeGen);
4704}
4705
Alexey Bataev7292c292016-04-25 12:22:29 +00004706/// Emit a helper variable and return corresponding lvalue.
4707static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4708 const ImplicitParamDecl *PVD,
4709 CodeGenFunction::OMPPrivateScope &Privates) {
4710 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4711 Privates.addPrivate(
4712 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4713}
4714
4715void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4716 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4717 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004718 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004719 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4720 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4721 const Expr *IfCond = nullptr;
4722 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4723 if (C->getNameModifier() == OMPD_unknown ||
4724 C->getNameModifier() == OMPD_taskloop) {
4725 IfCond = C->getCondition();
4726 break;
4727 }
4728 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004729
4730 OMPTaskDataTy Data;
4731 // Check if taskloop must be emitted without taskgroup.
4732 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004733 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004734 Data.Tied = true;
4735 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004736 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4737 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004738 Data.Schedule.setInt(/*IntVal=*/false);
4739 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004740 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4741 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004742 Data.Schedule.setInt(/*IntVal=*/true);
4743 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004744 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004745
4746 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4747 // if (PreCond) {
4748 // for (IV in 0..LastIteration) BODY;
4749 // <Final counter/linear vars updates>;
4750 // }
4751 //
4752
4753 // Emit: if (PreCond) - begin.
4754 // If the condition constant folds and can be elided, avoid emitting the
4755 // whole loop.
4756 bool CondConstant;
4757 llvm::BasicBlock *ContBlock = nullptr;
4758 OMPLoopScope PreInitScope(CGF, S);
4759 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4760 if (!CondConstant)
4761 return;
4762 } else {
4763 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4764 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4765 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4766 CGF.getProfileCount(&S));
4767 CGF.EmitBlock(ThenBlock);
4768 CGF.incrementProfileCounter(&S);
4769 }
4770
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004771 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4772 CGF.EmitOMPSimdInit(S);
4773
Alexey Bataev7292c292016-04-25 12:22:29 +00004774 OMPPrivateScope LoopScope(CGF);
4775 // Emit helper vars inits.
4776 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4777 auto *I = CS->getCapturedDecl()->param_begin();
4778 auto *LBP = std::next(I, LowerBound);
4779 auto *UBP = std::next(I, UpperBound);
4780 auto *STP = std::next(I, Stride);
4781 auto *LIP = std::next(I, LastIter);
4782 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4783 LoopScope);
4784 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4785 LoopScope);
4786 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4787 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4788 LoopScope);
4789 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004790 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004791 (void)LoopScope.Privatize();
4792 // Emit the loop iteration variable.
4793 const Expr *IVExpr = S.getIterationVariable();
4794 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4795 CGF.EmitVarDecl(*IVDecl);
4796 CGF.EmitIgnoredExpr(S.getInit());
4797
4798 // Emit the iterations count variable.
4799 // If it is not a variable, Sema decided to calculate iterations count on
4800 // each iteration (e.g., it is foldable into a constant).
4801 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4802 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4803 // Emit calculation of the iterations count.
4804 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4805 }
4806
4807 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4808 S.getInc(),
4809 [&S](CodeGenFunction &CGF) {
4810 CGF.EmitOMPLoopBody(S, JumpDest());
4811 CGF.EmitStopPoint(&S);
4812 },
4813 [](CodeGenFunction &) {});
4814 // Emit: if (PreCond) - end.
4815 if (ContBlock) {
4816 CGF.EmitBranch(ContBlock);
4817 CGF.EmitBlock(ContBlock, true);
4818 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004819 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4820 if (HasLastprivateClause) {
4821 CGF.EmitOMPLastprivateClauseFinal(
4822 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4823 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4824 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4825 (*LIP)->getType(), S.getLocStart())));
4826 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004827 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004828 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4829 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4830 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004831 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4832 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004833 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4834 OutlinedFn, SharedsTy,
4835 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004836 };
4837 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4838 CodeGen);
4839 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004840 if (Data.Nogroup) {
4841 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4842 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004843 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4844 *this,
4845 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4846 PrePostActionTy &Action) {
4847 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004848 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4849 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004850 },
4851 S.getLocStart());
4852 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004853}
4854
Alexey Bataev49f6e782015-12-01 04:18:41 +00004855void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004856 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004857}
4858
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004859void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4860 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004861 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004862}
Samuel Antao686c70c2016-05-26 17:30:50 +00004863
4864// Generate the instructions for '#pragma omp target update' directive.
4865void CodeGenFunction::EmitOMPTargetUpdateDirective(
4866 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004867 // If we don't have target devices, don't bother emitting the data mapping
4868 // code.
4869 if (CGM.getLangOpts().OMPTargetTriples.empty())
4870 return;
4871
4872 // Check if we have any if clause associated with the directive.
4873 const Expr *IfCond = nullptr;
4874 if (auto *C = S.getSingleClause<OMPIfClause>())
4875 IfCond = C->getCondition();
4876
4877 // Check if we have any device clause associated with the directive.
4878 const Expr *Device = nullptr;
4879 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4880 Device = C->getDevice();
4881
Alexey Bataev475a7442018-01-12 19:39:11 +00004882 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004883 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004884}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004885
4886void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4887 const OMPExecutableDirective &D) {
4888 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4889 return;
4890 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4891 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4892 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4893 } else {
4894 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4895 for (const auto *E : LD->counters()) {
4896 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4897 cast<DeclRefExpr>(E)->getDecl())) {
4898 // Emit only those that were not explicitly referenced in clauses.
4899 if (!CGF.LocalDeclMap.count(VD))
4900 CGF.EmitVarDecl(*VD);
4901 }
4902 }
4903 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004904 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004905 }
4906 };
4907 OMPSimdLexicalScope Scope(*this, D);
4908 CGM.getOpenMPRuntime().emitInlinedDirective(
4909 *this,
4910 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4911 : D.getDirectiveKind(),
4912 CodeGen);
4913}