blob: bf9a25722310f577b4e35be43832c7ab850ab87f [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 Bataevc2e88a82017-12-04 21:30:42 +0000123 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
126 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
127 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
128 });
129 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000130 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000131 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
132 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
133 for (const auto *I : PreInits->decls())
134 CGF.EmitVarDecl(cast<VarDecl>(*I));
135 }
136 }
137 }
138
139public:
140 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
141 : CodeGenFunction::RunCleanupsScope(CGF) {
142 emitPreInitStmt(CGF, S);
143 }
144};
145
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000146class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
147 CodeGenFunction::OMPPrivateScope InlinedShareds;
148
149 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
150 return CGF.LambdaCaptureFields.lookup(VD) ||
151 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
152 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
153 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
154 }
155
156public:
157 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
159 InlinedShareds(CGF) {
160 for (const auto *C : S.clauses()) {
161 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
162 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
163 for (const auto *I : PreInit->decls()) {
164 if (!I->hasAttr<OMPCaptureNoInitAttr>())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
166 else {
167 CodeGenFunction::AutoVarEmission Emission =
168 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
169 CGF.EmitAutoVarCleanups(Emission);
170 }
171 }
172 }
173 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
174 for (const Expr *E : UDP->varlists()) {
175 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
176 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
177 CGF.EmitVarDecl(*OED);
178 }
179 }
180 }
181 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
182 CGF.EmitOMPPrivateClause(S, InlinedShareds);
183 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
184 if (const Expr *E = TG->getReductionRef())
185 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
186 }
187 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
188 while (CS) {
189 for (auto &C : CS->captures()) {
190 if (C.capturesVariable() || C.capturesVariableByCopy()) {
191 auto *VD = C.getCapturedVar();
192 assert(VD == VD->getCanonicalDecl() &&
193 "Canonical decl must be captured.");
194 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
195 isCapturedVar(CGF, VD) ||
196 (CGF.CapturedStmtInfo &&
197 InlinedShareds.isGlobalVarCaptured(VD)),
198 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000199 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000200 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
201 return CGF.EmitLValue(&DRE).getAddress();
202 });
203 }
204 }
205 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
206 }
207 (void)InlinedShareds.Privatize();
208 }
209};
210
Alexey Bataev3392d762016-02-16 11:18:12 +0000211} // namespace
212
Alexey Bataevf8365372017-11-17 17:57:25 +0000213static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
214 const OMPExecutableDirective &S,
215 const RegionCodeGenTy &CodeGen);
216
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000217LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
218 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
220 OrigVD = OrigVD->getCanonicalDecl();
221 bool IsCaptured =
222 LambdaCaptureFields.lookup(OrigVD) ||
223 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
224 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
226 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
227 return EmitLValue(&DRE);
228 }
229 }
230 return EmitLValue(E);
231}
232
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
234 auto &C = getContext();
235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
239 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +0000240 auto VlaSize = getVLASize(VAT);
241 Ty = VlaSize.Type;
242 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
243 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000244 }
245 SizeInChars = C.getTypeSizeInChars(Ty);
246 if (SizeInChars.isZero())
247 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
248 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
249 } else
250 Size = CGM.getSize(SizeInChars);
251 return Size;
252}
253
Alexey Bataev2377fe92015-09-10 08:12:02 +0000254void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000255 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000256 const RecordDecl *RD = S.getCapturedRecordDecl();
257 auto CurField = RD->field_begin();
258 auto CurCap = S.captures().begin();
259 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
260 E = S.capture_init_end();
261 I != E; ++I, ++CurField, ++CurCap) {
262 if (CurField->hasCapturedVLAType()) {
263 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000264 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000265 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000266 } else if (CurCap->capturesThis())
267 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000268 else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000269 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000270
271 // If the field is not a pointer, we need to save the actual value
272 // and load it as a void pointer.
273 if (!CurField->getType()->isAnyPointerType()) {
274 auto &Ctx = getContext();
275 auto DstAddr = CreateMemTemp(
276 Ctx.getUIntPtrType(),
277 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
278 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
279
280 auto *SrcAddrVal = EmitScalarConversion(
281 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000282 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000283 LValue SrcLV =
284 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
285
286 // Store the value using the source type pointer.
287 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
288
289 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000290 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000291 }
292 CapturedVars.push_back(CV);
293 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000296 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 }
298}
299
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000300static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
301 QualType DstType, StringRef Name,
302 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000303 bool isReferenceType = false) {
304 ASTContext &Ctx = CGF.getContext();
305
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000306 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
307 Ctx.getUIntPtrType(),
308 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000309 auto TmpAddr =
310 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
311 .getAddress();
312
313 // If we are dealing with references we need to return the address of the
314 // reference instead of the reference of the value.
315 if (isReferenceType) {
316 QualType RefType = Ctx.getLValueReferenceType(DstType);
317 auto *RefVal = TmpAddr.getPointer();
318 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
319 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000320 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000321 }
322
323 return TmpAddr;
324}
325
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000326static QualType getCanonicalParamType(ASTContext &C, QualType T) {
327 if (T->isLValueReferenceType()) {
328 return C.getLValueReferenceType(
329 getCanonicalParamType(C, T.getNonReferenceType()),
330 /*SpelledAsLValue=*/false);
331 }
332 if (T->isPointerType())
333 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000334 if (auto *A = T->getAsArrayTypeUnsafe()) {
335 if (auto *VLA = dyn_cast<VariableArrayType>(A))
336 return getCanonicalParamType(C, VLA->getElementType());
337 else if (!A->isVariablyModifiedType())
338 return C.getCanonicalType(T);
339 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000340 return C.getCanonicalParamType(T);
341}
342
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343namespace {
344 /// Contains required data for proper outlined function codegen.
345 struct FunctionOptions {
346 /// Captured statement for which the function is generated.
347 const CapturedStmt *S = nullptr;
348 /// true if cast to/from UIntPtr is required for variables captured by
349 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000350 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000351 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000355 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000356 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
357 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000358 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000359 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
360 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000361 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000362 };
363}
364
Alexey Bataeve754b182017-08-09 19:38:53 +0000365static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000367 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000368 &LocalAddrs,
369 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
370 &VLASizes,
371 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
372 const CapturedDecl *CD = FO.S->getCapturedDecl();
373 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 assert(CD->hasBody() && "missing CapturedDecl body");
375
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000378 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000380 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000381 Args.append(CD->param_begin(),
382 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000383 TargetArgs.append(
384 CD->param_begin(),
385 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000387 FunctionDecl *DebugFunctionDecl = nullptr;
388 if (!FO.UIntPtrCastRequired) {
389 FunctionProtoType::ExtProtoInfo EPI;
390 DebugFunctionDecl = FunctionDecl::Create(
391 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
392 SourceLocation(), DeclarationName(), Ctx.VoidTy,
393 Ctx.getTrivialTypeSourceInfo(
394 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
395 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
396 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 for (auto *FD : RD->fields()) {
398 QualType ArgType = FD->getType();
399 IdentifierInfo *II = nullptr;
400 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000401
402 // If this is a capture by copy and the type is not a pointer, the outlined
403 // function argument type should be uintptr and the value properly casted to
404 // uintptr. This is necessary given that the runtime library is only able to
405 // deal with pointers. We can pass in the same way the VLA type sizes to the
406 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000407 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000409 if (FO.UIntPtrCastRequired)
410 ArgType = Ctx.getUIntPtrType();
411 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000412
413 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000414 CapVar = I->getCapturedVar();
415 II = CapVar->getIdentifier();
416 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 else {
419 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000420 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000421 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000422 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000423 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000424 VarDecl *Arg;
425 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
426 Arg = ParmVarDecl::Create(
427 Ctx, DebugFunctionDecl,
428 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
429 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
430 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
431 } else {
432 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
433 II, ArgType, ImplicitParamDecl::Other);
434 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000435 Args.emplace_back(Arg);
436 // Do not cast arguments if we emit function with non-original types.
437 TargetArgs.emplace_back(
438 FO.UIntPtrCastRequired
439 ? Arg
440 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 ++I;
442 }
443 Args.append(
444 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
445 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000446 TargetArgs.append(
447 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
448 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449
450 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000451 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000453 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
454
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000455 llvm::Function *F =
456 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
457 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
459 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000460 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000461
462 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000463 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
464 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000466 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000467 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000468 // Do not map arguments if we emit function with non-original types.
469 Address LocalAddr(Address::invalid());
470 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
471 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
472 TargetArgs[Cnt]);
473 } else {
474 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
475 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000476 // If we are capturing a pointer by copy we don't need to do anything, just
477 // use the value that we get from the arguments.
478 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000479 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000480 // If the variable is a reference we need to materialize it here.
481 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000482 Address RefAddr = CGF.CreateMemTemp(
483 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
484 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
485 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000486 LocalAddr = RefAddr;
487 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000488 if (!FO.RegisterCastedArgsOnly)
489 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000490 ++Cnt;
491 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000492 continue;
493 }
494
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000495 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
496 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000497 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000499 ArgLVal = CGF.MakeAddrLValue(
500 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
501 Args[Cnt]->getName(), ArgLVal),
502 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000503 }
Alexey Bataev1e491372018-01-23 18:44:14 +0000504 auto *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000506 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 } else if (I->capturesVariable()) {
508 auto *Var = I->getCapturedVar();
509 QualType VarTy = Var->getType();
510 Address ArgAddr = ArgLVal.getAddress();
511 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000512 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000513 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000514 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000517 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
518 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520 if (!FO.RegisterCastedArgsOnly) {
521 LocalAddrs.insert(
522 {Args[Cnt],
523 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
524 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000525 } else if (I->capturesVariableByCopy()) {
526 assert(!FD->getType()->isAnyPointerType() &&
527 "Not expecting a captured pointer.");
528 auto *Var = I->getCapturedVar();
529 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 LocalAddrs.insert(
531 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000532 {Var, FO.UIntPtrCastRequired
533 ? castValueFromUintptr(CGF, I->getLocation(),
534 FD->getType(), Args[Cnt]->getName(),
535 ArgLVal, VarTy->isReferenceType())
536 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000537 } else {
538 // If 'this' is captured, load it into CXXThisValue.
539 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000540 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000541 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000542 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000543 ++Cnt;
544 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000545 }
546
Alexey Bataeve754b182017-08-09 19:38:53 +0000547 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000548}
549
550llvm::Function *
551CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
552 assert(
553 CapturedStmtInfo &&
554 "CapturedStmtInfo should be set when generating the captured function");
555 const CapturedDecl *CD = S.getCapturedDecl();
556 // Build the argument list.
557 bool NeedWrapperFunction =
558 getDebugInfo() &&
559 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
560 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000561 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000562 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000563 SmallString<256> Buffer;
564 llvm::raw_svector_ostream Out(Buffer);
565 Out << CapturedStmtInfo->getHelperName();
566 if (NeedWrapperFunction)
567 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000568 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000569 Out.str());
570 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
571 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000572 for (const auto &LocalAddrPair : LocalAddrs) {
573 if (LocalAddrPair.second.first) {
574 setAddrOfLocalVar(LocalAddrPair.second.first,
575 LocalAddrPair.second.second);
576 }
577 }
578 for (const auto &VLASizePair : VLASizes)
579 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000580 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000581 CapturedStmtInfo->EmitBody(*this, CD->getBody());
582 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000583 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000584 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000585
Alexey Bataevefd884d2017-08-04 21:26:25 +0000586 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000587 /*RegisterCastedArgsOnly=*/true,
588 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 Args.clear();
591 LocalAddrs.clear();
592 VLASizes.clear();
593 llvm::Function *WrapperF =
594 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000595 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000596 llvm::SmallVector<llvm::Value *, 4> CallArgs;
597 for (const auto *Arg : Args) {
598 llvm::Value *CallArg;
599 auto I = LocalAddrs.find(Arg);
600 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000601 LValue LV = WrapperCGF.MakeAddrLValue(
602 I->second.second,
603 I->second.first ? I->second.first->getType() : Arg->getType(),
604 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000605 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 } else {
607 auto EI = VLASizes.find(Arg);
608 if (EI != VLASizes.end())
609 CallArg = EI->second.second;
610 else {
611 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000612 Arg->getType(),
613 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000614 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000615 }
616 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000617 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000618 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
620 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000621 WrapperCGF.FinishFunction();
622 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000623}
624
Alexey Bataev9959db52014-05-06 10:08:46 +0000625//===----------------------------------------------------------------------===//
626// OpenMP Directive Emission
627//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address DestAddr, Address SrcAddr, QualType OriginalType,
630 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000631 // Perform element-by-element initialization.
632 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000633
634 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000635 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000636 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
637 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
638
639 auto SrcBegin = SrcAddr.getPointer();
640 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
643 // The basic structure here is a while-do loop.
644 auto BodyBB = createBasicBlock("omp.arraycpy.body");
645 auto DoneBB = createBasicBlock("omp.arraycpy.done");
646 auto IsEmpty =
647 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
648 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000649
Alexey Bataev420d45b2015-04-14 05:11:24 +0000650 // Enter the loop body, making that address the current address.
651 auto EntryBB = Builder.GetInsertBlock();
652 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000653
654 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
655
656 llvm::PHINode *SrcElementPHI =
657 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
658 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
659 Address SrcElementCurrent =
660 Address(SrcElementPHI,
661 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
662
663 llvm::PHINode *DestElementPHI =
664 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
665 DestElementPHI->addIncoming(DestBegin, EntryBB);
666 Address DestElementCurrent =
667 Address(DestElementPHI,
668 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000669
Alexey Bataev420d45b2015-04-14 05:11:24 +0000670 // Emit copy.
671 CopyGen(DestElementCurrent, SrcElementCurrent);
672
673 // Shift the address forward by one element.
674 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000675 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000676 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000677 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000678 // Check whether we've reached the end.
679 auto Done =
680 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
681 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000682 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
683 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000684
685 // Done.
686 EmitBlock(DoneBB, /*IsFinished=*/true);
687}
688
John McCall7f416cc2015-09-08 08:05:57 +0000689void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
690 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 const VarDecl *SrcVD, const Expr *Copy) {
692 if (OriginalType->isArrayType()) {
693 auto *BO = dyn_cast<BinaryOperator>(Copy);
694 if (BO && BO->getOpcode() == BO_Assign) {
695 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000696 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
697 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
698 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000699 } else {
700 // For arrays with complex element types perform element by element
701 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000702 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000703 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000704 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 // Working with the single array element, so have to remap
706 // destination and source variables to corresponding array
707 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000708 CodeGenFunction::OMPPrivateScope Remap(*this);
709 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 return DestElement;
711 });
712 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000713 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000715 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000718 } else {
719 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000720 CodeGenFunction::OMPPrivateScope Remap(*this);
721 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
722 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000723 (void)Remap.Privatize();
724 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000725 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000727}
728
Alexey Bataev69c62a92015-04-15 04:52:20 +0000729bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
730 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000731 if (!HaveInsertPoint())
732 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000733 bool FirstprivateIsLastprivate = false;
734 llvm::DenseSet<const VarDecl *> Lastprivates;
735 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
736 for (const auto *D : C->varlists())
737 Lastprivates.insert(
738 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
739 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000740 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000741 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
742 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
743 // Force emission of the firstprivate copy if the directive does not emit
744 // outlined function, like omp for, omp simd, omp distribute etc.
745 bool MustEmitFirstprivateCopy =
746 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000747 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000748 auto IRef = C->varlist_begin();
749 auto InitsRef = C->inits().begin();
750 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000751 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752 bool ThisFirstprivateIsLastprivate =
753 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
754 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000755 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000756 !FD->getType()->isReferenceType()) {
757 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
758 ++IRef;
759 ++InitsRef;
760 continue;
761 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000762 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000763 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000764 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000765 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
766 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
767 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000768 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
769 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
770 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000771 LValue OriginalLVal = EmitLValue(&DRE);
772 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000773 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000774 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000775 // Emit VarDecl with copy init for arrays.
776 // Get the address of the original variable captured in current
777 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000778 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000779 auto Emission = EmitAutoVarAlloca(*VD);
780 auto *Init = VD->getInit();
781 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
782 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000783 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(),
784 Type);
785 EmitAggregateAssign(Dest, OriginalLVal, Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000786 } else {
787 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000788 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000789 [this, VDInit, Init](Address DestElement,
790 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000791 // Clean up any temporaries needed by the initialization.
792 RunCleanupsScope InitScope(*this);
793 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000794 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000795 EmitAnyExprToMem(Init, DestElement,
796 Init->getType().getQualifiers(),
797 /*IsInitializer*/ false);
798 LocalDeclMap.erase(VDInit);
799 });
800 }
801 EmitAutoVarCleanups(Emission);
802 return Emission.getAllocatedAddress();
803 });
804 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000805 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000806 // Emit private VarDecl with copy init.
807 // Remap temp VDInit variable to the address of the original
808 // variable
809 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000810 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000811 EmitDecl(*VD);
812 LocalDeclMap.erase(VDInit);
813 return GetAddrOfLocalVar(VD);
814 });
815 }
816 assert(IsRegistered &&
817 "firstprivate var already registered as private");
818 // Silence the warning about unused variable.
819 (void)IsRegistered;
820 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000821 ++IRef;
822 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000823 }
824 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000825 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000826}
827
Alexey Bataev03b340a2014-10-21 03:16:40 +0000828void CodeGenFunction::EmitOMPPrivateClause(
829 const OMPExecutableDirective &D,
830 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000831 if (!HaveInsertPoint())
832 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000833 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000834 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000835 auto IRef = C->varlist_begin();
836 for (auto IInit : C->private_copies()) {
837 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000838 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
839 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
840 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000841 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000842 // Emit private VarDecl with copy init.
843 EmitDecl(*VD);
844 return GetAddrOfLocalVar(VD);
845 });
846 assert(IsRegistered && "private var already registered as private");
847 // Silence the warning about unused variable.
848 (void)IsRegistered;
849 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000850 ++IRef;
851 }
852 }
853}
854
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000856 if (!HaveInsertPoint())
857 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000858 // threadprivate_var1 = master_threadprivate_var1;
859 // operator=(threadprivate_var2, master_threadprivate_var2);
860 // ...
861 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000862 llvm::DenseSet<const VarDecl *> CopiedVars;
863 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000864 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000865 auto IRef = C->varlist_begin();
866 auto ISrcRef = C->source_exprs().begin();
867 auto IDestRef = C->destination_exprs().begin();
868 for (auto *AssignOp : C->assignment_ops()) {
869 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000870 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000871 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000872 // Get the address of the master variable. If we are emitting code with
873 // TLS support, the address is passed from the master as field in the
874 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000875 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000876 if (getLangOpts().OpenMPUseTLS &&
877 getContext().getTargetInfo().isTLSSupported()) {
878 assert(CapturedStmtInfo->lookup(VD) &&
879 "Copyin threadprivates should have been captured!");
880 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
881 VK_LValue, (*IRef)->getExprLoc());
882 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000883 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000884 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000885 MasterAddr =
886 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
887 : CGM.GetAddrOfGlobal(VD),
888 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000889 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000890 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000891 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000892 if (CopiedVars.size() == 1) {
893 // At first check if current thread is a master thread. If it is, no
894 // need to copy data.
895 CopyBegin = createBasicBlock("copyin.not.master");
896 CopyEnd = createBasicBlock("copyin.not.master.end");
897 Builder.CreateCondBr(
898 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000899 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
900 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000901 CopyBegin, CopyEnd);
902 EmitBlock(CopyBegin);
903 }
904 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
905 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000906 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000907 }
908 ++IRef;
909 ++ISrcRef;
910 ++IDestRef;
911 }
912 }
913 if (CopyEnd) {
914 // Exit out of copying procedure for non-master thread.
915 EmitBlock(CopyEnd, /*IsFinished=*/true);
916 return true;
917 }
918 return false;
919}
920
Alexey Bataev38e89532015-04-16 04:54:05 +0000921bool CodeGenFunction::EmitOMPLastprivateClauseInit(
922 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000923 if (!HaveInsertPoint())
924 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000925 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000926 llvm::DenseSet<const VarDecl *> SIMDLCVs;
927 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
928 auto *LoopDirective = cast<OMPLoopDirective>(&D);
929 for (auto *C : LoopDirective->counters()) {
930 SIMDLCVs.insert(
931 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
932 }
933 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000934 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000936 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000937 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
938 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000939 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000940 auto IRef = C->varlist_begin();
941 auto IDestRef = C->destination_exprs().begin();
942 for (auto *IInit : C->private_copies()) {
943 // Keep the address of the original variable for future update at the end
944 // of the loop.
945 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000946 // Taskloops do not require additional initialization, it is done in
947 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000948 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
949 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000950 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000951 DeclRefExpr DRE(
952 const_cast<VarDecl *>(OrigVD),
953 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
954 OrigVD) != nullptr,
955 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
956 return EmitLValue(&DRE).getAddress();
957 });
958 // Check if the variable is also a firstprivate: in this case IInit is
959 // not generated. Initialization of this variable will happen in codegen
960 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000961 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000962 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000963 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
964 // Emit private VarDecl with copy init.
965 EmitDecl(*VD);
966 return GetAddrOfLocalVar(VD);
967 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000968 assert(IsRegistered &&
969 "lastprivate var already registered as private");
970 (void)IsRegistered;
971 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000972 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000973 ++IRef;
974 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000975 }
976 }
977 return HasAtLeastOneLastprivate;
978}
979
980void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000981 const OMPExecutableDirective &D, bool NoFinals,
982 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000983 if (!HaveInsertPoint())
984 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000985 // Emit following code:
986 // if (<IsLastIterCond>) {
987 // orig_var1 = private_orig_var1;
988 // ...
989 // orig_varn = private_orig_varn;
990 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000991 llvm::BasicBlock *ThenBB = nullptr;
992 llvm::BasicBlock *DoneBB = nullptr;
993 if (IsLastIterCond) {
994 ThenBB = createBasicBlock(".omp.lastprivate.then");
995 DoneBB = createBasicBlock(".omp.lastprivate.done");
996 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
997 EmitBlock(ThenBB);
998 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000999 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1000 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001001 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001002 auto IC = LoopDirective->counters().begin();
1003 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001004 auto *D =
1005 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1006 if (NoFinals)
1007 AlreadyEmittedVars.insert(D);
1008 else
1009 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001010 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001011 }
1012 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001013 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1014 auto IRef = C->varlist_begin();
1015 auto ISrcRef = C->source_exprs().begin();
1016 auto IDestRef = C->destination_exprs().begin();
1017 for (auto *AssignOp : C->assignment_ops()) {
1018 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1019 QualType Type = PrivateVD->getType();
1020 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1021 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1022 // If lastprivate variable is a loop control variable for loop-based
1023 // directive, update its value before copyin back to original
1024 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001025 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1026 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001027 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1028 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1029 // Get the address of the original variable.
1030 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1031 // Get the address of the private variable.
1032 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1033 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1034 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001035 Address(Builder.CreateLoad(PrivateAddr),
1036 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001037 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001038 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001039 ++IRef;
1040 ++ISrcRef;
1041 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001042 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001043 if (auto *PostUpdate = C->getPostUpdateExpr())
1044 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001045 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001046 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001047 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001048}
1049
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001050void CodeGenFunction::EmitOMPReductionClauseInit(
1051 const OMPExecutableDirective &D,
1052 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001053 if (!HaveInsertPoint())
1054 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001055 SmallVector<const Expr *, 4> Shareds;
1056 SmallVector<const Expr *, 4> Privates;
1057 SmallVector<const Expr *, 4> ReductionOps;
1058 SmallVector<const Expr *, 4> LHSs;
1059 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001060 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001061 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001062 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001063 auto ILHS = C->lhs_exprs().begin();
1064 auto IRHS = C->rhs_exprs().begin();
1065 for (const auto *Ref : C->varlists()) {
1066 Shareds.emplace_back(Ref);
1067 Privates.emplace_back(*IPriv);
1068 ReductionOps.emplace_back(*IRed);
1069 LHSs.emplace_back(*ILHS);
1070 RHSs.emplace_back(*IRHS);
1071 std::advance(IPriv, 1);
1072 std::advance(IRed, 1);
1073 std::advance(ILHS, 1);
1074 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001075 }
1076 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001077 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1078 unsigned Count = 0;
1079 auto ILHS = LHSs.begin();
1080 auto IRHS = RHSs.begin();
1081 auto IPriv = Privates.begin();
1082 for (const auto *IRef : Shareds) {
1083 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1084 // Emit private VarDecl with reduction init.
1085 RedCG.emitSharedLValue(*this, Count);
1086 RedCG.emitAggregateType(*this, Count);
1087 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1088 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1089 RedCG.getSharedLValue(Count),
1090 [&Emission](CodeGenFunction &CGF) {
1091 CGF.EmitAutoVarInit(Emission);
1092 return true;
1093 });
1094 EmitAutoVarCleanups(Emission);
1095 Address BaseAddr = RedCG.adjustPrivateAddress(
1096 *this, Count, Emission.getAllocatedAddress());
1097 bool IsRegistered = PrivateScope.addPrivate(
1098 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1099 assert(IsRegistered && "private var already registered as private");
1100 // Silence the warning about unused variable.
1101 (void)IsRegistered;
1102
1103 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1104 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001105 QualType Type = PrivateVD->getType();
1106 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1107 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001108 // Store the address of the original variable associated with the LHS
1109 // implicit variable.
1110 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1111 return RedCG.getSharedLValue(Count).getAddress();
1112 });
1113 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1114 return GetAddrOfLocalVar(PrivateVD);
1115 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001116 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1117 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001118 // Store the address of the original variable associated with the LHS
1119 // implicit variable.
1120 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1121 return RedCG.getSharedLValue(Count).getAddress();
1122 });
1123 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1124 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1125 ConvertTypeForMem(RHSVD->getType()),
1126 "rhs.begin");
1127 });
1128 } else {
1129 QualType Type = PrivateVD->getType();
1130 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1131 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1132 // Store the address of the original variable associated with the LHS
1133 // implicit variable.
1134 if (IsArray) {
1135 OriginalAddr = Builder.CreateElementBitCast(
1136 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1137 }
1138 PrivateScope.addPrivate(
1139 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1140 PrivateScope.addPrivate(
1141 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1142 return IsArray
1143 ? Builder.CreateElementBitCast(
1144 GetAddrOfLocalVar(PrivateVD),
1145 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1146 : GetAddrOfLocalVar(PrivateVD);
1147 });
1148 }
1149 ++ILHS;
1150 ++IRHS;
1151 ++IPriv;
1152 ++Count;
1153 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001154}
1155
1156void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001157 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001158 if (!HaveInsertPoint())
1159 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001160 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001161 llvm::SmallVector<const Expr *, 8> LHSExprs;
1162 llvm::SmallVector<const Expr *, 8> RHSExprs;
1163 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001165 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001166 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001167 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001168 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1169 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1170 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1171 }
1172 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001173 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1174 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001175 ReductionKind == OMPD_simd;
1176 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001177 // Emit nowait reduction if nowait clause is present or directive is a
1178 // parallel directive (it always has implicit barrier).
1179 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001180 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001181 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001182 }
1183}
1184
Alexey Bataev61205072016-03-02 04:57:40 +00001185static void emitPostUpdateForReductionClause(
1186 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1187 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1188 if (!CGF.HaveInsertPoint())
1189 return;
1190 llvm::BasicBlock *DoneBB = nullptr;
1191 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1192 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1193 if (!DoneBB) {
1194 if (auto *Cond = CondGen(CGF)) {
1195 // If the first post-update expression is found, emit conditional
1196 // block if it was requested.
1197 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1198 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1199 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1200 CGF.EmitBlock(ThenBB);
1201 }
1202 }
1203 CGF.EmitIgnoredExpr(PostUpdate);
1204 }
1205 }
1206 if (DoneBB)
1207 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1208}
1209
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001210namespace {
1211/// Codegen lambda for appending distribute lower and upper bounds to outlined
1212/// parallel function. This is necessary for combined constructs such as
1213/// 'distribute parallel for'
1214typedef llvm::function_ref<void(CodeGenFunction &,
1215 const OMPExecutableDirective &,
1216 llvm::SmallVectorImpl<llvm::Value *> &)>
1217 CodeGenBoundParametersTy;
1218} // anonymous namespace
1219
1220static void emitCommonOMPParallelDirective(
1221 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1222 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1223 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001224 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1225 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1226 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001227 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001228 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001229 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1230 /*IgnoreResultAssign*/ true);
1231 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1232 CGF, NumThreads, NumThreadsClause->getLocStart());
1233 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001234 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001235 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001236 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1237 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1238 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001239 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001240 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1241 if (C->getNameModifier() == OMPD_unknown ||
1242 C->getNameModifier() == OMPD_parallel) {
1243 IfCond = C->getCondition();
1244 break;
1245 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001246 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001247
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001248 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001249 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001250 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1251 // lower and upper bounds with the pragma 'for' chunking mechanism.
1252 // The following lambda takes care of appending the lower and upper bound
1253 // parameters when necessary
1254 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001255 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001256 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001257 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001258}
1259
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001260static void emitEmptyBoundParameters(CodeGenFunction &,
1261 const OMPExecutableDirective &,
1262 llvm::SmallVectorImpl<llvm::Value *> &) {}
1263
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001266 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001268 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001269 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1270 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001271 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001272 // propagation master's thread values of threadprivate variables to local
1273 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001274 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1275 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1276 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001277 }
1278 CGF.EmitOMPPrivateClause(S, PrivateScope);
1279 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1280 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001281 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001282 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001283 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001284 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1285 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001286 emitPostUpdateForReductionClause(
1287 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001288}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001289
Alexey Bataev0f34da12015-07-02 04:17:07 +00001290void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1291 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 RunCleanupsScope BodyScope(*this);
1293 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001294 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001295 EmitIgnoredExpr(I);
1296 }
Alexander Musman3276a272015-03-21 10:12:56 +00001297 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001298 // In distribute directives only loop counters may be marked as linear, no
1299 // need to generate the code for them.
1300 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1301 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1302 for (auto *U : C->updates())
1303 EmitIgnoredExpr(U);
1304 }
Alexander Musman3276a272015-03-21 10:12:56 +00001305 }
1306
Alexander Musmana5f070a2014-10-01 06:03:56 +00001307 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001308 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001309 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001310 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001311 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001312 // The end (updates/cleanups).
1313 EmitBlock(Continue.getBlock());
1314 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001315}
1316
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001317void CodeGenFunction::EmitOMPInnerLoop(
1318 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1319 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001320 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1321 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001322 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001323
1324 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001325 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001327 const SourceRange &R = S.getSourceRange();
1328 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1329 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001330
1331 // If there are any cleanups between here and the loop-exit scope,
1332 // create a block to stage a loop exit along.
1333 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001334 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001335 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336
Alexander Musmand196ef22014-10-07 08:57:09 +00001337 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338
Alexey Bataev2df54a02015-03-12 08:53:29 +00001339 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001340 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001341 if (ExitBlock != LoopExit.getBlock()) {
1342 EmitBlock(ExitBlock);
1343 EmitBranchThroughCleanup(LoopExit);
1344 }
1345
1346 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001347 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348
1349 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001350 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001351 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1352
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001353 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001354
1355 // Emit "IV = IV + 1" and a back-edge to the condition block.
1356 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001357 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001358 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001359 BreakContinueStack.pop_back();
1360 EmitBranch(CondBlock);
1361 LoopStack.pop();
1362 // Emit the fall-through block.
1363 EmitBlock(LoopExit.getBlock());
1364}
1365
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001366bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001367 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001368 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001369 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001370 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001371 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001372 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001373 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001374 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001375 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1376 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1377 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1378 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1379 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1380 VD->getInit()->getType(), VK_LValue,
1381 VD->getInit()->getExprLoc());
1382 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1383 VD->getType()),
1384 /*capturedByInit=*/false);
1385 EmitAutoVarCleanups(Emission);
1386 } else
1387 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001388 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001389 // Emit the linear steps for the linear clauses.
1390 // If a step is not constant, it is pre-calculated before the loop.
1391 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1392 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001393 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001394 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001395 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001396 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001397 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001398 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001399}
1400
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401void CodeGenFunction::EmitOMPLinearClauseFinal(
1402 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001403 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001404 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001405 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001406 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001407 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001408 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001409 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001411 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001413 // If the first post-update expression is found, emit conditional
1414 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001415 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1416 DoneBB = createBasicBlock(".omp.linear.pu.done");
1417 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1418 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001419 }
1420 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1422 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001423 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001424 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001425 Address OrigAddr = EmitLValue(&DRE).getAddress();
1426 CodeGenFunction::OMPPrivateScope VarScope(*this);
1427 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001428 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001429 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001430 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001431 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001432 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001434 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001435 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001436 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001437}
1438
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001439static void emitAlignedClause(CodeGenFunction &CGF,
1440 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001441 if (!CGF.HaveInsertPoint())
1442 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001443 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001444 unsigned ClauseAlignment = 0;
1445 if (auto AlignmentExpr = Clause->getAlignment()) {
1446 auto AlignmentCI =
1447 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1448 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001449 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001450 for (auto E : Clause->varlists()) {
1451 unsigned Alignment = ClauseAlignment;
1452 if (Alignment == 0) {
1453 // OpenMP [2.8.1, Description]
1454 // If no optional parameter is specified, implementation-defined default
1455 // alignments for SIMD instructions on the target platforms are assumed.
1456 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001457 CGF.getContext()
1458 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1459 E->getType()->getPointeeType()))
1460 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001461 }
1462 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1463 "alignment is not power of 2");
1464 if (Alignment != 0) {
1465 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1466 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1467 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001468 }
1469 }
1470}
1471
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001472void CodeGenFunction::EmitOMPPrivateLoopCounters(
1473 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1474 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001475 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001476 auto I = S.private_counters().begin();
1477 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001478 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1479 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001480 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001481 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001482 if (!LocalDeclMap.count(PrivateVD)) {
1483 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1484 EmitAutoVarCleanups(VarEmission);
1485 }
1486 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1487 /*RefersToEnclosingVariableOrCapture=*/false,
1488 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1489 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001490 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001491 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1492 VD->hasGlobalStorage()) {
1493 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1494 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1495 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1496 E->getType(), VK_LValue, E->getExprLoc());
1497 return EmitLValue(&DRE).getAddress();
1498 });
1499 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001500 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001501 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001502}
1503
Alexey Bataev62dbb972015-04-22 11:59:37 +00001504static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1505 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1506 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001507 if (!CGF.HaveInsertPoint())
1508 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001509 {
1510 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001511 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001513 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001514 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001515 CGF.EmitIgnoredExpr(I);
1516 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001517 }
1518 // Check that loop is executed at least one time.
1519 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1520}
1521
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001522void CodeGenFunction::EmitOMPLinearClause(
1523 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1524 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001525 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001526 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1527 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1528 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1529 for (auto *C : LoopDirective->counters()) {
1530 SIMDLCVs.insert(
1531 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1532 }
1533 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001534 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001535 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001536 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001537 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1538 auto *PrivateVD =
1539 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001540 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1541 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1542 // Emit private VarDecl with copy init.
1543 EmitVarDecl(*PrivateVD);
1544 return GetAddrOfLocalVar(PrivateVD);
1545 });
1546 assert(IsRegistered && "linear var already registered as private");
1547 // Silence the warning about unused variable.
1548 (void)IsRegistered;
1549 } else
1550 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001551 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001552 }
1553 }
1554}
1555
Alexey Bataev45bfad52015-08-21 12:19:04 +00001556static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001557 const OMPExecutableDirective &D,
1558 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001559 if (!CGF.HaveInsertPoint())
1560 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001561 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001562 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1563 /*ignoreResult=*/true);
1564 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1565 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1566 // In presence of finite 'safelen', it may be unsafe to mark all
1567 // the memory instructions parallel, because loop-carried
1568 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001569 if (!IsMonotonic)
1570 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001571 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001572 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1573 /*ignoreResult=*/true);
1574 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001575 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001576 // In presence of finite 'safelen', it may be unsafe to mark all
1577 // the memory instructions parallel, because loop-carried
1578 // dependences of 'safelen' iterations are possible.
1579 CGF.LoopStack.setParallel(false);
1580 }
1581}
1582
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001583void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1584 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001585 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001586 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001587 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001588 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001589}
1590
Alexey Bataevef549a82016-03-09 09:49:09 +00001591void CodeGenFunction::EmitOMPSimdFinal(
1592 const OMPLoopDirective &D,
1593 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001594 if (!HaveInsertPoint())
1595 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001596 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001597 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001598 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001599 for (auto F : D.finals()) {
1600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001601 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1602 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1603 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1604 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001605 if (!DoneBB) {
1606 if (auto *Cond = CondGen(*this)) {
1607 // If the first post-update expression is found, emit conditional
1608 // block if it was requested.
1609 auto *ThenBB = createBasicBlock(".omp.final.then");
1610 DoneBB = createBasicBlock(".omp.final.done");
1611 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1612 EmitBlock(ThenBB);
1613 }
1614 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001615 Address OrigAddr = Address::invalid();
1616 if (CED)
1617 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1618 else {
1619 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1620 /*RefersToEnclosingVariableOrCapture=*/false,
1621 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1622 OrigAddr = EmitLValue(&DRE).getAddress();
1623 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001624 OMPPrivateScope VarScope(*this);
1625 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001626 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001627 (void)VarScope.Privatize();
1628 EmitIgnoredExpr(F);
1629 }
1630 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001631 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001633 if (DoneBB)
1634 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001635}
1636
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001637static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1638 const OMPLoopDirective &S,
1639 CodeGenFunction::JumpDest LoopExit) {
1640 CGF.EmitOMPLoopBody(S, LoopExit);
1641 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001642}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001643
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001644/// Emit a helper variable and return corresponding lvalue.
1645static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1646 const DeclRefExpr *Helper) {
1647 auto VDecl = cast<VarDecl>(Helper->getDecl());
1648 CGF.EmitVarDecl(*VDecl);
1649 return CGF.EmitLValue(Helper);
1650}
1651
Alexey Bataevf8365372017-11-17 17:57:25 +00001652static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1653 PrePostActionTy &Action) {
1654 Action.Enter(CGF);
1655 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1656 "Expected simd directive");
1657 OMPLoopScope PreInitScope(CGF, S);
1658 // if (PreCond) {
1659 // for (IV in 0..LastIteration) BODY;
1660 // <Final counter/linear vars updates>;
1661 // }
1662 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001663 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1664 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1665 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1666 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1667 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1668 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001669
Alexey Bataevf8365372017-11-17 17:57:25 +00001670 // Emit: if (PreCond) - begin.
1671 // If the condition constant folds and can be elided, avoid emitting the
1672 // whole loop.
1673 bool CondConstant;
1674 llvm::BasicBlock *ContBlock = nullptr;
1675 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1676 if (!CondConstant)
1677 return;
1678 } else {
1679 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1680 ContBlock = CGF.createBasicBlock("simd.if.end");
1681 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1682 CGF.getProfileCount(&S));
1683 CGF.EmitBlock(ThenBlock);
1684 CGF.incrementProfileCounter(&S);
1685 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001686
Alexey Bataevf8365372017-11-17 17:57:25 +00001687 // Emit the loop iteration variable.
1688 const Expr *IVExpr = S.getIterationVariable();
1689 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1690 CGF.EmitVarDecl(*IVDecl);
1691 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001692
Alexey Bataevf8365372017-11-17 17:57:25 +00001693 // Emit the iterations count variable.
1694 // If it is not a variable, Sema decided to calculate iterations count on
1695 // each iteration (e.g., it is foldable into a constant).
1696 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1697 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1698 // Emit calculation of the iterations count.
1699 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1700 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001701
Alexey Bataevf8365372017-11-17 17:57:25 +00001702 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001703
Alexey Bataevf8365372017-11-17 17:57:25 +00001704 emitAlignedClause(CGF, S);
1705 (void)CGF.EmitOMPLinearClauseInit(S);
1706 {
1707 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1708 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1709 CGF.EmitOMPLinearClause(S, LoopScope);
1710 CGF.EmitOMPPrivateClause(S, LoopScope);
1711 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1712 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1713 (void)LoopScope.Privatize();
1714 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1715 S.getInc(),
1716 [&S](CodeGenFunction &CGF) {
1717 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1718 CGF.EmitStopPoint(&S);
1719 },
1720 [](CodeGenFunction &) {});
1721 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001722 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001723 // Emit final copy of the lastprivate variables at the end of loops.
1724 if (HasLastprivateClause)
1725 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1726 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1727 emitPostUpdateForReductionClause(
1728 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1729 }
1730 CGF.EmitOMPLinearClauseFinal(
1731 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1732 // Emit: if (PreCond) - end.
1733 if (ContBlock) {
1734 CGF.EmitBranch(ContBlock);
1735 CGF.EmitBlock(ContBlock, true);
1736 }
1737}
1738
1739void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1740 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1741 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001742 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001743 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001744 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001745}
1746
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001747void CodeGenFunction::EmitOMPOuterLoop(
1748 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1749 CodeGenFunction::OMPPrivateScope &LoopScope,
1750 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1751 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1752 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001753 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001754
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001755 const Expr *IVExpr = S.getIterationVariable();
1756 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1757 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1758
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001759 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1760
1761 // Start the loop with a block that tests the condition.
1762 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1763 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001764 const SourceRange &R = S.getSourceRange();
1765 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1766 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001767
1768 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001769 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001770 // UB = min(UB, GlobalUB) or
1771 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1772 // 'distribute parallel for')
1773 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001774 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001775 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001777 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001778 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001779 BoolCondVal =
1780 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1781 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001782 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001783
1784 // If there are any cleanups between here and the loop-exit scope,
1785 // create a block to stage a loop exit along.
1786 auto ExitBlock = LoopExit.getBlock();
1787 if (LoopScope.requiresCleanups())
1788 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1789
1790 auto LoopBody = createBasicBlock("omp.dispatch.body");
1791 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1792 if (ExitBlock != LoopExit.getBlock()) {
1793 EmitBlock(ExitBlock);
1794 EmitBranchThroughCleanup(LoopExit);
1795 }
1796 EmitBlock(LoopBody);
1797
Alexander Musman92bdaab2015-03-12 13:37:50 +00001798 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1799 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001800 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001801 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001802
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001803 // Create a block for the increment.
1804 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1805 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1806
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001807 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1808 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001809 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1810 LoopStack.setParallel(!IsMonotonic);
1811 else
1812 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001813
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001814 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001815
1816 // when 'distribute' is not combined with a 'for':
1817 // while (idx <= UB) { BODY; ++idx; }
1818 // when 'distribute' is combined with a 'for'
1819 // (e.g. 'distribute parallel for')
1820 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1821 EmitOMPInnerLoop(
1822 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1823 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1824 CodeGenLoop(CGF, S, LoopExit);
1825 },
1826 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1827 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1828 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001829
1830 EmitBlock(Continue.getBlock());
1831 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001832 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001833 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001834 EmitIgnoredExpr(LoopArgs.NextLB);
1835 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001836 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001837
1838 EmitBranch(CondBlock);
1839 LoopStack.pop();
1840 // Emit the fall-through block.
1841 EmitBlock(LoopExit.getBlock());
1842
1843 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001844 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1845 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001846 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1847 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001848 };
1849 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001850}
1851
1852void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001853 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001854 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001855 const OMPLoopArguments &LoopArgs,
1856 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001857 auto &RT = CGM.getOpenMPRuntime();
1858
1859 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001860 const bool DynamicOrOrdered =
1861 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001862
1863 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001864 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001865 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001866 "static non-chunked schedule does not need outer loop");
1867
1868 // Emit outer loop.
1869 //
1870 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1871 // When schedule(dynamic,chunk_size) is specified, the iterations are
1872 // distributed to threads in the team in chunks as the threads request them.
1873 // Each thread executes a chunk of iterations, then requests another chunk,
1874 // until no chunks remain to be distributed. Each chunk contains chunk_size
1875 // iterations, except for the last chunk to be distributed, which may have
1876 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1877 //
1878 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1879 // to threads in the team in chunks as the executing threads request them.
1880 // Each thread executes a chunk of iterations, then requests another chunk,
1881 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1882 // each chunk is proportional to the number of unassigned iterations divided
1883 // by the number of threads in the team, decreasing to 1. For a chunk_size
1884 // with value k (greater than 1), the size of each chunk is determined in the
1885 // same way, with the restriction that the chunks do not contain fewer than k
1886 // iterations (except for the last chunk to be assigned, which may have fewer
1887 // than k iterations).
1888 //
1889 // When schedule(auto) is specified, the decision regarding scheduling is
1890 // delegated to the compiler and/or runtime system. The programmer gives the
1891 // implementation the freedom to choose any possible mapping of iterations to
1892 // threads in the team.
1893 //
1894 // When schedule(runtime) is specified, the decision regarding scheduling is
1895 // deferred until run time, and the schedule and chunk size are taken from the
1896 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1897 // implementation defined
1898 //
1899 // while(__kmpc_dispatch_next(&LB, &UB)) {
1900 // idx = LB;
1901 // while (idx <= UB) { BODY; ++idx;
1902 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1903 // } // inner loop
1904 // }
1905 //
1906 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1907 // When schedule(static, chunk_size) is specified, iterations are divided into
1908 // chunks of size chunk_size, and the chunks are assigned to the threads in
1909 // the team in a round-robin fashion in the order of the thread number.
1910 //
1911 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1912 // while (idx <= UB) { BODY; ++idx; } // inner loop
1913 // LB = LB + ST;
1914 // UB = UB + ST;
1915 // }
1916 //
1917
1918 const Expr *IVExpr = S.getIterationVariable();
1919 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1920 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1921
1922 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001923 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1924 llvm::Value *LBVal = DispatchBounds.first;
1925 llvm::Value *UBVal = DispatchBounds.second;
1926 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1927 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001928 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001929 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001930 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001931 CGOpenMPRuntime::StaticRTInput StaticInit(
1932 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1933 LoopArgs.ST, LoopArgs.Chunk);
1934 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1935 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001936 }
1937
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001938 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1939 const unsigned IVSize,
1940 const bool IVSigned) {
1941 if (Ordered) {
1942 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1943 IVSigned);
1944 }
1945 };
1946
1947 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1948 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1949 OuterLoopArgs.IncExpr = S.getInc();
1950 OuterLoopArgs.Init = S.getInit();
1951 OuterLoopArgs.Cond = S.getCond();
1952 OuterLoopArgs.NextLB = S.getNextLowerBound();
1953 OuterLoopArgs.NextUB = S.getNextUpperBound();
1954 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1955 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001956}
1957
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001958static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1959 const unsigned IVSize, const bool IVSigned) {}
1960
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001961void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001962 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1963 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1964 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001965
1966 auto &RT = CGM.getOpenMPRuntime();
1967
1968 // Emit outer loop.
1969 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1970 // dynamic
1971 //
1972
1973 const Expr *IVExpr = S.getIterationVariable();
1974 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1975 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1976
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001977 CGOpenMPRuntime::StaticRTInput StaticInit(
1978 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1979 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1980 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001981
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001982 // for combined 'distribute' and 'for' the increment expression of distribute
1983 // is store in DistInc. For 'distribute' alone, it is in Inc.
1984 Expr *IncExpr;
1985 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1986 IncExpr = S.getDistInc();
1987 else
1988 IncExpr = S.getInc();
1989
1990 // this routine is shared by 'omp distribute parallel for' and
1991 // 'omp distribute': select the right EUB expression depending on the
1992 // directive
1993 OMPLoopArguments OuterLoopArgs;
1994 OuterLoopArgs.LB = LoopArgs.LB;
1995 OuterLoopArgs.UB = LoopArgs.UB;
1996 OuterLoopArgs.ST = LoopArgs.ST;
1997 OuterLoopArgs.IL = LoopArgs.IL;
1998 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1999 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2000 ? S.getCombinedEnsureUpperBound()
2001 : S.getEnsureUpperBound();
2002 OuterLoopArgs.IncExpr = IncExpr;
2003 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2004 ? S.getCombinedInit()
2005 : S.getInit();
2006 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2007 ? S.getCombinedCond()
2008 : S.getCond();
2009 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2010 ? S.getCombinedNextLowerBound()
2011 : S.getNextLowerBound();
2012 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2013 ? S.getCombinedNextUpperBound()
2014 : S.getNextUpperBound();
2015
2016 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2017 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2018 emitEmptyOrdered);
2019}
2020
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002021static std::pair<LValue, LValue>
2022emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2023 const OMPExecutableDirective &S) {
2024 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2025 LValue LB =
2026 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2027 LValue UB =
2028 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2029
2030 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2031 // parallel for') we need to use the 'distribute'
2032 // chunk lower and upper bounds rather than the whole loop iteration
2033 // space. These are parameters to the outlined function for 'parallel'
2034 // and we copy the bounds of the previous schedule into the
2035 // the current ones.
2036 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2037 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002038 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2039 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002040 PrevLBVal = CGF.EmitScalarConversion(
2041 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002042 LS.getIterationVariable()->getType(),
2043 LS.getPrevLowerBoundVariable()->getExprLoc());
2044 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2045 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002046 PrevUBVal = CGF.EmitScalarConversion(
2047 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002048 LS.getIterationVariable()->getType(),
2049 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002050
2051 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2052 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2053
2054 return {LB, UB};
2055}
2056
2057/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2058/// we need to use the LB and UB expressions generated by the worksharing
2059/// code generation support, whereas in non combined situations we would
2060/// just emit 0 and the LastIteration expression
2061/// This function is necessary due to the difference of the LB and UB
2062/// types for the RT emission routines for 'for_static_init' and
2063/// 'for_dispatch_init'
2064static std::pair<llvm::Value *, llvm::Value *>
2065emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2066 const OMPExecutableDirective &S,
2067 Address LB, Address UB) {
2068 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2069 const Expr *IVExpr = LS.getIterationVariable();
2070 // when implementing a dynamic schedule for a 'for' combined with a
2071 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2072 // is not normalized as each team only executes its own assigned
2073 // distribute chunk
2074 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002075 llvm::Value *LBVal =
2076 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2077 llvm::Value *UBVal =
2078 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002079 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002080}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002081
2082static void emitDistributeParallelForDistributeInnerBoundParams(
2083 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2084 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2085 const auto &Dir = cast<OMPLoopDirective>(S);
2086 LValue LB =
2087 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2088 auto LBCast = CGF.Builder.CreateIntCast(
2089 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2090 CapturedVars.push_back(LBCast);
2091 LValue UB =
2092 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2093
2094 auto UBCast = CGF.Builder.CreateIntCast(
2095 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2096 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002097}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002098
2099static void
2100emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2101 const OMPLoopDirective &S,
2102 CodeGenFunction::JumpDest LoopExit) {
2103 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2104 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002105 bool HasCancel = false;
2106 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2107 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2108 HasCancel = D->hasCancel();
2109 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2110 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002111 else if (const auto *D =
2112 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2113 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002114 }
2115 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2116 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002117 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2118 emitDistributeParallelForInnerBounds,
2119 emitDistributeParallelForDispatchBounds);
2120 };
2121
2122 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002123 CGF, S,
2124 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2125 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002126 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002127}
2128
Carlo Bertolli9925f152016-06-27 14:55:37 +00002129void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2130 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002131 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2132 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2133 S.getDistInc());
2134 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002135 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002136 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002137}
2138
Kelvin Li4a39add2016-07-05 05:00:15 +00002139void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2140 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002141 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2142 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2143 S.getDistInc());
2144 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002145 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002146 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002147}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002148
2149void CodeGenFunction::EmitOMPDistributeSimdDirective(
2150 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002151 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2152 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2153 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002154 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002155 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002156}
2157
Alexey Bataevf8365372017-11-17 17:57:25 +00002158void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2159 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2160 // Emit SPMD target parallel for region as a standalone region.
2161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2162 emitOMPSimdRegion(CGF, S, Action);
2163 };
2164 llvm::Function *Fn;
2165 llvm::Constant *Addr;
2166 // Emit target region as a standalone region.
2167 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2168 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2169 assert(Fn && Addr && "Target device function emission failed.");
2170}
2171
Kelvin Li986330c2016-07-20 22:57:10 +00002172void CodeGenFunction::EmitOMPTargetSimdDirective(
2173 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002174 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2175 emitOMPSimdRegion(CGF, S, Action);
2176 };
2177 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002178}
2179
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002180namespace {
2181 struct ScheduleKindModifiersTy {
2182 OpenMPScheduleClauseKind Kind;
2183 OpenMPScheduleClauseModifier M1;
2184 OpenMPScheduleClauseModifier M2;
2185 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2186 OpenMPScheduleClauseModifier M1,
2187 OpenMPScheduleClauseModifier M2)
2188 : Kind(Kind), M1(M1), M2(M2) {}
2189 };
2190} // namespace
2191
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002192bool CodeGenFunction::EmitOMPWorksharingLoop(
2193 const OMPLoopDirective &S, Expr *EUB,
2194 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2195 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002196 // Emit the loop iteration variable.
2197 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2198 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2199 EmitVarDecl(*IVDecl);
2200
2201 // Emit the iterations count variable.
2202 // If it is not a variable, Sema decided to calculate iterations count on each
2203 // iteration (e.g., it is foldable into a constant).
2204 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2205 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2206 // Emit calculation of the iterations count.
2207 EmitIgnoredExpr(S.getCalcLastIteration());
2208 }
2209
2210 auto &RT = CGM.getOpenMPRuntime();
2211
Alexey Bataev38e89532015-04-16 04:54:05 +00002212 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002213 // Check pre-condition.
2214 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002215 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002216 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002217 // If the condition constant folds and can be elided, avoid emitting the
2218 // whole loop.
2219 bool CondConstant;
2220 llvm::BasicBlock *ContBlock = nullptr;
2221 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2222 if (!CondConstant)
2223 return false;
2224 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002225 auto *ThenBlock = createBasicBlock("omp.precond.then");
2226 ContBlock = createBasicBlock("omp.precond.end");
2227 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002228 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002229 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002230 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002231 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002232
Alexey Bataevea33dee2018-02-15 23:39:43 +00002233 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002234 bool Ordered = false;
2235 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2236 if (OrderedClause->getNumForLoops())
2237 RT.emitDoacrossInit(*this, S);
2238 else
2239 Ordered = true;
2240 }
2241
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002242 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002243 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002244 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002245 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002246
2247 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2248 LValue LB = Bounds.first;
2249 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002250 LValue ST =
2251 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2252 LValue IL =
2253 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2254
Alexander Musmanc6388682014-12-15 07:07:06 +00002255 // Emit 'then' code.
2256 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002257 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002258 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002259 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002260 // initialization of firstprivate variables and post-update of
2261 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002262 CGM.getOpenMPRuntime().emitBarrierCall(
2263 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2264 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002265 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002266 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002267 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002268 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002269 EmitOMPPrivateLoopCounters(S, LoopScope);
2270 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002271 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002272
2273 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002274 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002275 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002276 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002277 ScheduleKind.Schedule = C->getScheduleKind();
2278 ScheduleKind.M1 = C->getFirstScheduleModifier();
2279 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002280 if (const auto *Ch = C->getChunkSize()) {
2281 Chunk = EmitScalarExpr(Ch);
2282 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2283 S.getIterationVariable()->getType(),
2284 S.getLocStart());
2285 }
2286 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002287 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2288 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002289 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2290 // If the static schedule kind is specified or if the ordered clause is
2291 // specified, and if no monotonic modifier is specified, the effect will
2292 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002293 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002294 /* Chunked */ Chunk != nullptr) &&
2295 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002296 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2297 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002298 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2299 // When no chunk_size is specified, the iteration space is divided into
2300 // chunks that are approximately equal in size, and at most one chunk is
2301 // distributed to each thread. Note that the size of the chunks is
2302 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002303 CGOpenMPRuntime::StaticRTInput StaticInit(
2304 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2305 UB.getAddress(), ST.getAddress());
2306 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2307 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002308 auto LoopExit =
2309 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002310 // UB = min(UB, GlobalUB);
2311 EmitIgnoredExpr(S.getEnsureUpperBound());
2312 // IV = LB;
2313 EmitIgnoredExpr(S.getInit());
2314 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002315 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2316 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002317 [&S, LoopExit](CodeGenFunction &CGF) {
2318 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002319 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002320 },
2321 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002322 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002323 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002324 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002325 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2326 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002327 };
2328 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002329 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002330 const bool IsMonotonic =
2331 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2332 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2333 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2334 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002335 // Emit the outer loop, which requests its work chunk [LB..UB] from
2336 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002337 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2338 ST.getAddress(), IL.getAddress(),
2339 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002340 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002341 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002342 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002343 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2344 EmitOMPSimdFinal(S,
2345 [&](CodeGenFunction &CGF) -> llvm::Value * {
2346 return CGF.Builder.CreateIsNotNull(
2347 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2348 });
2349 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002350 EmitOMPReductionClauseFinal(
2351 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2352 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2353 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002354 // Emit post-update of the reduction variables if IsLastIter != 0.
2355 emitPostUpdateForReductionClause(
2356 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2357 return CGF.Builder.CreateIsNotNull(
2358 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2359 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002360 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2361 if (HasLastprivateClause)
2362 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002363 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2364 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002365 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002366 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002367 return CGF.Builder.CreateIsNotNull(
2368 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2369 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002370 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002371 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002372 if (ContBlock) {
2373 EmitBranch(ContBlock);
2374 EmitBlock(ContBlock, true);
2375 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002376 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002377 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002378}
2379
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002380/// The following two functions generate expressions for the loop lower
2381/// and upper bounds in case of static and dynamic (dispatch) schedule
2382/// of the associated 'for' or 'distribute' loop.
2383static std::pair<LValue, LValue>
2384emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2385 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2386 LValue LB =
2387 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2388 LValue UB =
2389 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2390 return {LB, UB};
2391}
2392
2393/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2394/// consider the lower and upper bound expressions generated by the
2395/// worksharing loop support, but we use 0 and the iteration space size as
2396/// constants
2397static std::pair<llvm::Value *, llvm::Value *>
2398emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2399 Address LB, Address UB) {
2400 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2401 const Expr *IVExpr = LS.getIterationVariable();
2402 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2403 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2404 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2405 return {LBVal, UBVal};
2406}
2407
Alexander Musmanc6388682014-12-15 07:07:06 +00002408void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002409 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002410 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2411 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002412 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002413 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2414 emitForLoopBounds,
2415 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002416 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002417 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002418 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002419 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2420 S.hasCancel());
2421 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002422
2423 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002424 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002425 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2426 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002427}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002428
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002429void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002430 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002431 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2432 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002433 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2434 emitForLoopBounds,
2435 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002436 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002437 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002438 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002439 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2440 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002441
2442 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002443 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002444 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2445 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002446}
2447
Alexey Bataev2df54a02015-03-12 08:53:29 +00002448static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2449 const Twine &Name,
2450 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002451 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002452 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002453 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002454 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002455}
2456
Alexey Bataev3392d762016-02-16 11:18:12 +00002457void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002458 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2459 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002460 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002461 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2462 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002463 auto &C = CGF.CGM.getContext();
2464 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2465 // Emit helper vars inits.
2466 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2467 CGF.Builder.getInt32(0));
2468 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2469 : CGF.Builder.getInt32(0);
2470 LValue UB =
2471 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2472 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2473 CGF.Builder.getInt32(1));
2474 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2475 CGF.Builder.getInt32(0));
2476 // Loop counter.
2477 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2478 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2479 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2480 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2481 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2482 // Generate condition for loop.
2483 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002484 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 // Increment for loop counter.
2486 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002487 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002488 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2489 // Iterate through all sections and emit a switch construct:
2490 // switch (IV) {
2491 // case 0:
2492 // <SectionStmt[0]>;
2493 // break;
2494 // ...
2495 // case <NumSection> - 1:
2496 // <SectionStmt[<NumSection> - 1]>;
2497 // break;
2498 // }
2499 // .omp.sections.exit:
2500 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002501 auto *SwitchStmt =
2502 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2503 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002504 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002505 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002506 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002507 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2508 CGF.EmitBlock(CaseBB);
2509 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002510 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002511 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002512 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002513 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002514 } else {
2515 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2516 CGF.EmitBlock(CaseBB);
2517 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2518 CGF.EmitStmt(Stmt);
2519 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002520 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002521 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002522 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002523
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002524 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2525 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002526 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002527 // initialization of firstprivate variables and post-update of lastprivate
2528 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002529 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2530 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2531 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002532 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002533 CGF.EmitOMPPrivateClause(S, LoopScope);
2534 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2535 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2536 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002537
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002538 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002539 OpenMPScheduleTy ScheduleKind;
2540 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002541 CGOpenMPRuntime::StaticRTInput StaticInit(
2542 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2543 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002544 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002545 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002546 // UB = min(UB, GlobalUB);
2547 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2548 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2549 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2550 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2551 // IV = LB;
2552 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2553 // while (idx <= UB) { BODY; ++idx; }
2554 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2555 [](CodeGenFunction &) {});
2556 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002557 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002558 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2559 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002560 };
2561 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002562 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002563 // Emit post-update of the reduction variables if IsLastIter != 0.
2564 emitPostUpdateForReductionClause(
2565 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2566 return CGF.Builder.CreateIsNotNull(
2567 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2568 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002569
2570 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2571 if (HasLastprivates)
2572 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002573 S, /*NoFinals=*/false,
2574 CGF.Builder.CreateIsNotNull(
2575 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002576 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002577
2578 bool HasCancel = false;
2579 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2580 HasCancel = OSD->hasCancel();
2581 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2582 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002583 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002584 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2585 HasCancel);
2586 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2587 // clause. Otherwise the barrier will be generated by the codegen for the
2588 // directive.
2589 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002590 // Emit implicit barrier to synchronize threads and avoid data races on
2591 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002592 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2593 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002594 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002595}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002596
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002597void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002598 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002599 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002600 EmitSections(S);
2601 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002602 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002603 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002604 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2605 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002606 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002607}
2608
2609void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002610 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002611 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002612 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002613 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002614 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2615 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002616}
2617
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002618void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002619 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002620 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002621 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002622 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002623 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002624 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002625 // Build a list of copyprivate variables along with helper expressions
2626 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002627 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002628 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002629 DestExprs.append(C->destination_exprs().begin(),
2630 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002631 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002632 AssignmentOps.append(C->assignment_ops().begin(),
2633 C->assignment_ops().end());
2634 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002635 // Emit code for 'single' region along with 'copyprivate' clauses
2636 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2637 Action.Enter(CGF);
2638 OMPPrivateScope SingleScope(CGF);
2639 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2640 CGF.EmitOMPPrivateClause(S, SingleScope);
2641 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002642 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002643 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002644 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002645 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002646 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2647 CopyprivateVars, DestExprs,
2648 SrcExprs, AssignmentOps);
2649 }
2650 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2651 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002652 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002653 CGM.getOpenMPRuntime().emitBarrierCall(
2654 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002655 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002656 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002657}
2658
Alexey Bataev8d690652014-12-04 07:23:53 +00002659void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002660 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2661 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002662 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002663 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002664 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002665 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002666}
2667
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002668void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002669 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2670 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002671 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002672 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002673 Expr *Hint = nullptr;
2674 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2675 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002676 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002677 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2678 S.getDirectiveName().getAsString(),
2679 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002680}
2681
Alexey Bataev671605e2015-04-13 05:28:11 +00002682void CodeGenFunction::EmitOMPParallelForDirective(
2683 const OMPParallelForDirective &S) {
2684 // Emit directive as a combined directive that consists of two implicit
2685 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002686 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002687 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002688 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2689 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002690 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002691 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2692 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002693}
2694
Alexander Musmane4e893b2014-09-23 09:33:00 +00002695void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002696 const OMPParallelForSimdDirective &S) {
2697 // Emit directive as a combined directive that consists of two implicit
2698 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002699 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002700 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2701 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002702 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002703 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2704 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002705}
2706
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002707void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002708 const OMPParallelSectionsDirective &S) {
2709 // Emit directive as a combined directive that consists of two implicit
2710 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002711 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2712 CGF.EmitSections(S);
2713 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002714 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2715 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002716}
2717
Alexey Bataev475a7442018-01-12 19:39:11 +00002718void CodeGenFunction::EmitOMPTaskBasedDirective(
2719 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2720 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2721 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002722 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002723 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002724 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002725 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002726 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002727 // Check if the task is final
2728 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2729 // If the condition constant folds and can be elided, try to avoid emitting
2730 // the condition and the dead arm of the if/else.
2731 auto *Cond = Clause->getCondition();
2732 bool CondConstant;
2733 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2734 Data.Final.setInt(CondConstant);
2735 else
2736 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2737 } else {
2738 // By default the task is not final.
2739 Data.Final.setInt(/*IntVal=*/false);
2740 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002741 // Check if the task has 'priority' clause.
2742 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002743 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002744 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002745 Data.Priority.setPointer(EmitScalarConversion(
2746 EmitScalarExpr(Prio), Prio->getType(),
2747 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2748 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002749 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002750 // The first function argument for tasks is a thread id, the second one is a
2751 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002752 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2753 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002754 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002755 auto IRef = C->varlist_begin();
2756 for (auto *IInit : C->private_copies()) {
2757 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2758 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002759 Data.PrivateVars.push_back(*IRef);
2760 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002761 }
2762 ++IRef;
2763 }
2764 }
2765 EmittedAsPrivate.clear();
2766 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002767 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002768 auto IRef = C->varlist_begin();
2769 auto IElemInitRef = C->inits().begin();
2770 for (auto *IInit : C->private_copies()) {
2771 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2772 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002773 Data.FirstprivateVars.push_back(*IRef);
2774 Data.FirstprivateCopies.push_back(IInit);
2775 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002776 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002777 ++IRef;
2778 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002779 }
2780 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002781 // Get list of lastprivate variables (for taskloops).
2782 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2783 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2784 auto IRef = C->varlist_begin();
2785 auto ID = C->destination_exprs().begin();
2786 for (auto *IInit : C->private_copies()) {
2787 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2788 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2789 Data.LastprivateVars.push_back(*IRef);
2790 Data.LastprivateCopies.push_back(IInit);
2791 }
2792 LastprivateDstsOrigs.insert(
2793 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2794 cast<DeclRefExpr>(*IRef)});
2795 ++IRef;
2796 ++ID;
2797 }
2798 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002799 SmallVector<const Expr *, 4> LHSs;
2800 SmallVector<const Expr *, 4> RHSs;
2801 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2802 auto IPriv = C->privates().begin();
2803 auto IRed = C->reduction_ops().begin();
2804 auto ILHS = C->lhs_exprs().begin();
2805 auto IRHS = C->rhs_exprs().begin();
2806 for (const auto *Ref : C->varlists()) {
2807 Data.ReductionVars.emplace_back(Ref);
2808 Data.ReductionCopies.emplace_back(*IPriv);
2809 Data.ReductionOps.emplace_back(*IRed);
2810 LHSs.emplace_back(*ILHS);
2811 RHSs.emplace_back(*IRHS);
2812 std::advance(IPriv, 1);
2813 std::advance(IRed, 1);
2814 std::advance(ILHS, 1);
2815 std::advance(IRHS, 1);
2816 }
2817 }
2818 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2819 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002820 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002821 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2822 for (auto *IRef : C->varlists())
2823 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002824 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2825 CapturedRegion](CodeGenFunction &CGF,
2826 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002827 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002828 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002829 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2830 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002831 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002832 auto *CopyFn = CGF.Builder.CreateLoad(
2833 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2834 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2835 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2836 // Map privates.
2837 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2838 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2839 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002840 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002841 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2842 Address PrivatePtr = CGF.CreateMemTemp(
2843 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2844 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2845 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002846 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002847 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002848 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2849 Address PrivatePtr =
2850 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2851 ".firstpriv.ptr.addr");
2852 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2853 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002854 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002855 for (auto *E : Data.LastprivateVars) {
2856 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2857 Address PrivatePtr =
2858 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2859 ".lastpriv.ptr.addr");
2860 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2861 CallArgs.push_back(PrivatePtr.getPointer());
2862 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002863 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2864 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002865 for (auto &&Pair : LastprivateDstsOrigs) {
2866 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2867 DeclRefExpr DRE(
2868 const_cast<VarDecl *>(OrigVD),
2869 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2870 OrigVD) != nullptr,
2871 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2872 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2873 return CGF.EmitLValue(&DRE).getAddress();
2874 });
2875 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002876 for (auto &&Pair : PrivatePtrs) {
2877 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2878 CGF.getContext().getDeclAlign(Pair.first));
2879 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2880 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002881 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002882 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002883 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002884 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2885 Data.ReductionOps);
2886 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2887 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2888 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2889 RedCG.emitSharedLValue(CGF, Cnt);
2890 RedCG.emitAggregateType(CGF, Cnt);
2891 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2892 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2893 Replacement =
2894 Address(CGF.EmitScalarConversion(
2895 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2896 CGF.getContext().getPointerType(
2897 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002898 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002899 Replacement.getAlignment());
2900 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2901 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2902 [Replacement]() { return Replacement; });
2903 // FIXME: This must removed once the runtime library is fixed.
2904 // Emit required threadprivate variables for
2905 // initilizer/combiner/finalizer.
2906 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2907 RedCG, Cnt);
2908 }
2909 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002910 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002911 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002912 SmallVector<const Expr *, 4> InRedVars;
2913 SmallVector<const Expr *, 4> InRedPrivs;
2914 SmallVector<const Expr *, 4> InRedOps;
2915 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2916 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2917 auto IPriv = C->privates().begin();
2918 auto IRed = C->reduction_ops().begin();
2919 auto ITD = C->taskgroup_descriptors().begin();
2920 for (const auto *Ref : C->varlists()) {
2921 InRedVars.emplace_back(Ref);
2922 InRedPrivs.emplace_back(*IPriv);
2923 InRedOps.emplace_back(*IRed);
2924 TaskgroupDescriptors.emplace_back(*ITD);
2925 std::advance(IPriv, 1);
2926 std::advance(IRed, 1);
2927 std::advance(ITD, 1);
2928 }
2929 }
2930 // Privatize in_reduction items here, because taskgroup descriptors must be
2931 // privatized earlier.
2932 OMPPrivateScope InRedScope(CGF);
2933 if (!InRedVars.empty()) {
2934 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2935 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2936 RedCG.emitSharedLValue(CGF, Cnt);
2937 RedCG.emitAggregateType(CGF, Cnt);
2938 // The taskgroup descriptor variable is always implicit firstprivate and
2939 // privatized already during procoessing of the firstprivates.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002940 llvm::Value *ReductionsPtr =
2941 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2942 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002943 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2944 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2945 Replacement = Address(
2946 CGF.EmitScalarConversion(
2947 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2948 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002949 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002950 Replacement.getAlignment());
2951 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2952 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2953 [Replacement]() { return Replacement; });
2954 // FIXME: This must removed once the runtime library is fixed.
2955 // Emit required threadprivate variables for
2956 // initilizer/combiner/finalizer.
2957 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2958 RedCG, Cnt);
2959 }
2960 }
2961 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002962
2963 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002964 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002965 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002966 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2967 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2968 Data.NumberOfParts);
2969 OMPLexicalScope Scope(*this, S);
2970 TaskGen(*this, OutlinedFn, Data);
2971}
2972
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002973static ImplicitParamDecl *
2974createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002975 QualType Ty, CapturedDecl *CD,
2976 SourceLocation Loc) {
2977 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2978 ImplicitParamDecl::Other);
2979 auto *OrigRef = DeclRefExpr::Create(
2980 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2981 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2982 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2983 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002984 auto *PrivateRef = DeclRefExpr::Create(
2985 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002986 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002987 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002988 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2989 ImplicitParamDecl::Other);
2990 auto *InitRef = DeclRefExpr::Create(
2991 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2992 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002993 PrivateVD->setInitStyle(VarDecl::CInit);
2994 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2995 InitRef, /*BasePath=*/nullptr,
2996 VK_RValue));
2997 Data.FirstprivateVars.emplace_back(OrigRef);
2998 Data.FirstprivateCopies.emplace_back(PrivateRef);
2999 Data.FirstprivateInits.emplace_back(InitRef);
3000 return OrigVD;
3001}
3002
3003void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3004 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3005 OMPTargetDataInfo &InputInfo) {
3006 // Emit outlined function for task construct.
3007 auto CS = S.getCapturedStmt(OMPD_task);
3008 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3009 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3010 auto *I = CS->getCapturedDecl()->param_begin();
3011 auto *PartId = std::next(I);
3012 auto *TaskT = std::next(I, 4);
3013 OMPTaskDataTy Data;
3014 // The task is not final.
3015 Data.Final.setInt(/*IntVal=*/false);
3016 // Get list of firstprivate variables.
3017 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3018 auto IRef = C->varlist_begin();
3019 auto IElemInitRef = C->inits().begin();
3020 for (auto *IInit : C->private_copies()) {
3021 Data.FirstprivateVars.push_back(*IRef);
3022 Data.FirstprivateCopies.push_back(IInit);
3023 Data.FirstprivateInits.push_back(*IElemInitRef);
3024 ++IRef;
3025 ++IElemInitRef;
3026 }
3027 }
3028 OMPPrivateScope TargetScope(*this);
3029 VarDecl *BPVD = nullptr;
3030 VarDecl *PVD = nullptr;
3031 VarDecl *SVD = nullptr;
3032 if (InputInfo.NumberOfTargetItems > 0) {
3033 auto *CD = CapturedDecl::Create(
3034 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3035 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3036 QualType BaseAndPointersType = getContext().getConstantArrayType(
3037 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3038 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003039 BPVD = createImplicitFirstprivateForType(
3040 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3041 PVD = createImplicitFirstprivateForType(
3042 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003043 QualType SizesType = getContext().getConstantArrayType(
3044 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3045 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003046 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3047 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003048 TargetScope.addPrivate(
3049 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3050 TargetScope.addPrivate(PVD,
3051 [&InputInfo]() { return InputInfo.PointersArray; });
3052 TargetScope.addPrivate(SVD,
3053 [&InputInfo]() { return InputInfo.SizesArray; });
3054 }
3055 (void)TargetScope.Privatize();
3056 // Build list of dependences.
3057 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3058 for (auto *IRef : C->varlists())
3059 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3060 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3061 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3062 // Set proper addresses for generated private copies.
3063 OMPPrivateScope Scope(CGF);
3064 if (!Data.FirstprivateVars.empty()) {
3065 enum { PrivatesParam = 2, CopyFnParam = 3 };
3066 auto *CopyFn = CGF.Builder.CreateLoad(
3067 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3068 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3069 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3070 // Map privates.
3071 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3072 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3073 CallArgs.push_back(PrivatesPtr);
3074 for (auto *E : Data.FirstprivateVars) {
3075 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3076 Address PrivatePtr =
3077 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3078 ".firstpriv.ptr.addr");
3079 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3080 CallArgs.push_back(PrivatePtr.getPointer());
3081 }
3082 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3083 CopyFn, CallArgs);
3084 for (auto &&Pair : PrivatePtrs) {
3085 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3086 CGF.getContext().getDeclAlign(Pair.first));
3087 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3088 }
3089 }
3090 // Privatize all private variables except for in_reduction items.
3091 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003092 if (InputInfo.NumberOfTargetItems > 0) {
3093 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3094 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3095 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3096 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3097 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3098 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3099 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003100
3101 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003102 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003103 BodyGen(CGF);
3104 };
3105 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3106 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3107 Data.NumberOfParts);
3108 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3109 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3110 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3111 SourceLocation());
3112
3113 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3114 SharedsTy, CapturedStruct, &IfCond, Data);
3115}
3116
Alexey Bataev7292c292016-04-25 12:22:29 +00003117void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3118 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003119 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003120 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003121 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003122 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003123 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3124 if (C->getNameModifier() == OMPD_unknown ||
3125 C->getNameModifier() == OMPD_task) {
3126 IfCond = C->getCondition();
3127 break;
3128 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003129 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003130
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003131 OMPTaskDataTy Data;
3132 // Check if we should emit tied or untied task.
3133 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003134 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3135 CGF.EmitStmt(CS->getCapturedStmt());
3136 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003137 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003138 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003139 const OMPTaskDataTy &Data) {
3140 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3141 SharedsTy, CapturedStruct, IfCond,
3142 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003143 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003144 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003145}
3146
Alexey Bataev9f797f32015-02-05 05:57:51 +00003147void CodeGenFunction::EmitOMPTaskyieldDirective(
3148 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003149 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003150}
3151
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003152void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003153 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003154}
3155
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003156void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3157 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003158}
3159
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003160void CodeGenFunction::EmitOMPTaskgroupDirective(
3161 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003162 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3163 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003164 if (const Expr *E = S.getReductionRef()) {
3165 SmallVector<const Expr *, 4> LHSs;
3166 SmallVector<const Expr *, 4> RHSs;
3167 OMPTaskDataTy Data;
3168 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3169 auto IPriv = C->privates().begin();
3170 auto IRed = C->reduction_ops().begin();
3171 auto ILHS = C->lhs_exprs().begin();
3172 auto IRHS = C->rhs_exprs().begin();
3173 for (const auto *Ref : C->varlists()) {
3174 Data.ReductionVars.emplace_back(Ref);
3175 Data.ReductionCopies.emplace_back(*IPriv);
3176 Data.ReductionOps.emplace_back(*IRed);
3177 LHSs.emplace_back(*ILHS);
3178 RHSs.emplace_back(*IRHS);
3179 std::advance(IPriv, 1);
3180 std::advance(IRed, 1);
3181 std::advance(ILHS, 1);
3182 std::advance(IRHS, 1);
3183 }
3184 }
3185 llvm::Value *ReductionDesc =
3186 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3187 LHSs, RHSs, Data);
3188 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3189 CGF.EmitVarDecl(*VD);
3190 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3191 /*Volatile=*/false, E->getType());
3192 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003193 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003194 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003195 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003196 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3197}
3198
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003199void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003200 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003201 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003202 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3203 FlushClause->varlist_end());
3204 }
3205 return llvm::None;
3206 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003207}
3208
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003209void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3210 const CodeGenLoopTy &CodeGenLoop,
3211 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003212 // Emit the loop iteration variable.
3213 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3214 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3215 EmitVarDecl(*IVDecl);
3216
3217 // Emit the iterations count variable.
3218 // If it is not a variable, Sema decided to calculate iterations count on each
3219 // iteration (e.g., it is foldable into a constant).
3220 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3221 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3222 // Emit calculation of the iterations count.
3223 EmitIgnoredExpr(S.getCalcLastIteration());
3224 }
3225
3226 auto &RT = CGM.getOpenMPRuntime();
3227
Carlo Bertolli962bb802017-01-03 18:24:42 +00003228 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003229 // Check pre-condition.
3230 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003231 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003232 // Skip the entire loop if we don't meet the precondition.
3233 // If the condition constant folds and can be elided, avoid emitting the
3234 // whole loop.
3235 bool CondConstant;
3236 llvm::BasicBlock *ContBlock = nullptr;
3237 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3238 if (!CondConstant)
3239 return;
3240 } else {
3241 auto *ThenBlock = createBasicBlock("omp.precond.then");
3242 ContBlock = createBasicBlock("omp.precond.end");
3243 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3244 getProfileCount(&S));
3245 EmitBlock(ThenBlock);
3246 incrementProfileCounter(&S);
3247 }
3248
Alexey Bataev617db5f2017-12-04 15:38:33 +00003249 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003250 // Emit 'then' code.
3251 {
3252 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003253
3254 LValue LB = EmitOMPHelperVar(
3255 *this, cast<DeclRefExpr>(
3256 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3257 ? S.getCombinedLowerBoundVariable()
3258 : S.getLowerBoundVariable())));
3259 LValue UB = EmitOMPHelperVar(
3260 *this, cast<DeclRefExpr>(
3261 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3262 ? S.getCombinedUpperBoundVariable()
3263 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003264 LValue ST =
3265 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3266 LValue IL =
3267 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3268
3269 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003270 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003271 // Emit implicit barrier to synchronize threads and avoid data races
3272 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003273 // lastprivate variables.
3274 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003275 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3276 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003277 }
3278 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003279 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003280 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3281 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003282 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003283 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003284 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003285 (void)LoopScope.Privatize();
3286
3287 // Detect the distribute schedule kind and chunk.
3288 llvm::Value *Chunk = nullptr;
3289 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3290 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3291 ScheduleKind = C->getDistScheduleKind();
3292 if (const auto *Ch = C->getChunkSize()) {
3293 Chunk = EmitScalarExpr(Ch);
3294 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003295 S.getIterationVariable()->getType(),
3296 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003297 }
3298 }
3299 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3300 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3301
3302 // OpenMP [2.10.8, distribute Construct, Description]
3303 // If dist_schedule is specified, kind must be static. If specified,
3304 // iterations are divided into chunks of size chunk_size, chunks are
3305 // assigned to the teams of the league in a round-robin fashion in the
3306 // order of the team number. When no chunk_size is specified, the
3307 // iteration space is divided into chunks that are approximately equal
3308 // in size, and at most one chunk is distributed to each team of the
3309 // league. The size of the chunks is unspecified in this case.
3310 if (RT.isStaticNonchunked(ScheduleKind,
3311 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003312 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3313 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003314 CGOpenMPRuntime::StaticRTInput StaticInit(
3315 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3316 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003318 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003319 auto LoopExit =
3320 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3321 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003322 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3323 ? S.getCombinedEnsureUpperBound()
3324 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003325 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003326 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3327 ? S.getCombinedInit()
3328 : S.getInit());
3329
3330 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3331 ? S.getCombinedCond()
3332 : S.getCond();
3333
3334 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003335 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003336 // when combined with 'for' (e.g. as in 'distribute parallel for')
3337 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3338 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3339 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3340 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003341 },
3342 [](CodeGenFunction &) {});
3343 EmitBlock(LoopExit.getBlock());
3344 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003345 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003346 } else {
3347 // Emit the outer loop, which requests its work chunk [LB..UB] from
3348 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003349 const OMPLoopArguments LoopArguments = {
3350 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3351 Chunk};
3352 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3353 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003354 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003355 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3356 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3357 return CGF.Builder.CreateIsNotNull(
3358 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3359 });
3360 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003361 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3362 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3363 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3364 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3365 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3366 isOpenMPSimdDirective(S.getDirectiveKind())) {
3367 ReductionKind = OMPD_parallel_for_simd;
3368 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3369 ReductionKind = OMPD_parallel_for;
3370 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3371 ReductionKind = OMPD_simd;
3372 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3373 S.hasClausesOfKind<OMPReductionClause>()) {
3374 llvm_unreachable(
3375 "No reduction clauses is allowed in distribute directive.");
3376 }
3377 EmitOMPReductionClauseFinal(S, ReductionKind);
3378 // Emit post-update of the reduction variables if IsLastIter != 0.
3379 emitPostUpdateForReductionClause(
3380 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3381 return CGF.Builder.CreateIsNotNull(
3382 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3383 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003384 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003385 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003386 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003387 EmitOMPLastprivateClauseFinal(
3388 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003389 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3390 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003391 }
3392
3393 // We're now done with the loop, so jump to the continuation block.
3394 if (ContBlock) {
3395 EmitBranch(ContBlock);
3396 EmitBlock(ContBlock, true);
3397 }
3398 }
3399}
3400
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003401void CodeGenFunction::EmitOMPDistributeDirective(
3402 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003403 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003404
3405 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003406 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003407 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003408 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003409}
3410
Alexey Bataev5f600d62015-09-29 03:48:57 +00003411static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3412 const CapturedStmt *S) {
3413 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3414 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3415 CGF.CapturedStmtInfo = &CapStmtInfo;
3416 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3417 Fn->addFnAttr(llvm::Attribute::NoInline);
3418 return Fn;
3419}
3420
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003421void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003422 if (S.hasClausesOfKind<OMPDependClause>()) {
3423 assert(!S.getAssociatedStmt() &&
3424 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003425 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3426 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003427 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003428 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003429 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003430 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3431 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003432 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003433 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003434 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3435 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3436 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003437 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3438 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003439 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003440 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003441 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003442 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003443 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003444 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003445 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003446}
3447
Alexey Bataevb57056f2015-01-22 06:17:56 +00003448static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003449 QualType SrcType, QualType DestType,
3450 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003451 assert(CGF.hasScalarEvaluationKind(DestType) &&
3452 "DestType must have scalar evaluation kind.");
3453 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3454 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003455 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3456 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003457 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003458 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003459}
3460
3461static CodeGenFunction::ComplexPairTy
3462convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003463 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003464 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3465 "DestType must have complex evaluation kind.");
3466 CodeGenFunction::ComplexPairTy ComplexVal;
3467 if (Val.isScalar()) {
3468 // Convert the input element to the element type of the complex.
3469 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003470 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3471 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003472 ComplexVal = CodeGenFunction::ComplexPairTy(
3473 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3474 } else {
3475 assert(Val.isComplex() && "Must be a scalar or complex.");
3476 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3477 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3478 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003479 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003480 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003481 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003482 }
3483 return ComplexVal;
3484}
3485
Alexey Bataev5e018f92015-04-23 06:35:10 +00003486static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3487 LValue LVal, RValue RVal) {
3488 if (LVal.isGlobalReg()) {
3489 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3490 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003491 CGF.EmitAtomicStore(RVal, LVal,
3492 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3493 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003494 LVal.isVolatile(), /*IsInit=*/false);
3495 }
3496}
3497
Alexey Bataev8524d152016-01-21 12:35:58 +00003498void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3499 QualType RValTy, SourceLocation Loc) {
3500 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003501 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003502 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3503 *this, RVal, RValTy, LVal.getType(), Loc)),
3504 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003505 break;
3506 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003507 EmitStoreOfComplex(
3508 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003509 /*isInit=*/false);
3510 break;
3511 case TEK_Aggregate:
3512 llvm_unreachable("Must be a scalar or complex.");
3513 }
3514}
3515
Alexey Bataevb57056f2015-01-22 06:17:56 +00003516static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3517 const Expr *X, const Expr *V,
3518 SourceLocation Loc) {
3519 // v = x;
3520 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3521 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3522 LValue XLValue = CGF.EmitLValue(X);
3523 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003524 RValue Res = XLValue.isGlobalReg()
3525 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003526 : CGF.EmitAtomicLoad(
3527 XLValue, Loc,
3528 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3529 : llvm::AtomicOrdering::Monotonic,
3530 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003531 // OpenMP, 2.12.6, atomic Construct
3532 // Any atomic construct with a seq_cst clause forces the atomically
3533 // performed operation to include an implicit flush operation without a
3534 // list.
3535 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003536 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003537 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003538}
3539
Alexey Bataevb8329262015-02-27 06:33:30 +00003540static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3541 const Expr *X, const Expr *E,
3542 SourceLocation Loc) {
3543 // x = expr;
3544 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003545 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003546 // OpenMP, 2.12.6, atomic Construct
3547 // Any atomic construct with a seq_cst clause forces the atomically
3548 // performed operation to include an implicit flush operation without a
3549 // list.
3550 if (IsSeqCst)
3551 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3552}
3553
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003554static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3555 RValue Update,
3556 BinaryOperatorKind BO,
3557 llvm::AtomicOrdering AO,
3558 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003559 auto &Context = CGF.CGM.getContext();
3560 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003561 // expression is simple and atomic is allowed for the given type for the
3562 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003563 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003564 !Update.getScalarVal()->getType()->isIntegerTy() ||
3565 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3566 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003567 X.getAddress().getElementType())) ||
3568 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003569 !Context.getTargetInfo().hasBuiltinAtomic(
3570 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003571 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003572
3573 llvm::AtomicRMWInst::BinOp RMWOp;
3574 switch (BO) {
3575 case BO_Add:
3576 RMWOp = llvm::AtomicRMWInst::Add;
3577 break;
3578 case BO_Sub:
3579 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003580 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003581 RMWOp = llvm::AtomicRMWInst::Sub;
3582 break;
3583 case BO_And:
3584 RMWOp = llvm::AtomicRMWInst::And;
3585 break;
3586 case BO_Or:
3587 RMWOp = llvm::AtomicRMWInst::Or;
3588 break;
3589 case BO_Xor:
3590 RMWOp = llvm::AtomicRMWInst::Xor;
3591 break;
3592 case BO_LT:
3593 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3594 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3595 : llvm::AtomicRMWInst::Max)
3596 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3597 : llvm::AtomicRMWInst::UMax);
3598 break;
3599 case BO_GT:
3600 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3601 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3602 : llvm::AtomicRMWInst::Min)
3603 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3604 : llvm::AtomicRMWInst::UMin);
3605 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003606 case BO_Assign:
3607 RMWOp = llvm::AtomicRMWInst::Xchg;
3608 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003609 case BO_Mul:
3610 case BO_Div:
3611 case BO_Rem:
3612 case BO_Shl:
3613 case BO_Shr:
3614 case BO_LAnd:
3615 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003616 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003617 case BO_PtrMemD:
3618 case BO_PtrMemI:
3619 case BO_LE:
3620 case BO_GE:
3621 case BO_EQ:
3622 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003623 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003624 case BO_AddAssign:
3625 case BO_SubAssign:
3626 case BO_AndAssign:
3627 case BO_OrAssign:
3628 case BO_XorAssign:
3629 case BO_MulAssign:
3630 case BO_DivAssign:
3631 case BO_RemAssign:
3632 case BO_ShlAssign:
3633 case BO_ShrAssign:
3634 case BO_Comma:
3635 llvm_unreachable("Unsupported atomic update operation");
3636 }
3637 auto *UpdateVal = Update.getScalarVal();
3638 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3639 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003640 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003641 X.getType()->hasSignedIntegerRepresentation());
3642 }
John McCall7f416cc2015-09-08 08:05:57 +00003643 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003644 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003645}
3646
Alexey Bataev5e018f92015-04-23 06:35:10 +00003647std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003648 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3649 llvm::AtomicOrdering AO, SourceLocation Loc,
3650 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3651 // Update expressions are allowed to have the following forms:
3652 // x binop= expr; -> xrval + expr;
3653 // x++, ++x -> xrval + 1;
3654 // x--, --x -> xrval - 1;
3655 // x = x binop expr; -> xrval binop expr
3656 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003657 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3658 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003659 if (X.isGlobalReg()) {
3660 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3661 // 'xrval'.
3662 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3663 } else {
3664 // Perform compare-and-swap procedure.
3665 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003666 }
3667 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003668 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003669}
3670
3671static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3672 const Expr *X, const Expr *E,
3673 const Expr *UE, bool IsXLHSInRHSPart,
3674 SourceLocation Loc) {
3675 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3676 "Update expr in 'atomic update' must be a binary operator.");
3677 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3678 // Update expressions are allowed to have the following forms:
3679 // x binop= expr; -> xrval + expr;
3680 // x++, ++x -> xrval + 1;
3681 // x--, --x -> xrval - 1;
3682 // x = x binop expr; -> xrval binop expr
3683 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003684 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003685 LValue XLValue = CGF.EmitLValue(X);
3686 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003687 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3688 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003689 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3690 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3691 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3692 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3693 auto Gen =
3694 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3695 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3696 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3697 return CGF.EmitAnyExpr(UE);
3698 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003699 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3700 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3701 // OpenMP, 2.12.6, atomic Construct
3702 // Any atomic construct with a seq_cst clause forces the atomically
3703 // performed operation to include an implicit flush operation without a
3704 // list.
3705 if (IsSeqCst)
3706 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3707}
3708
3709static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003710 QualType SourceType, QualType ResType,
3711 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003712 switch (CGF.getEvaluationKind(ResType)) {
3713 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003714 return RValue::get(
3715 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003716 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003717 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003718 return RValue::getComplex(Res.first, Res.second);
3719 }
3720 case TEK_Aggregate:
3721 break;
3722 }
3723 llvm_unreachable("Must be a scalar or complex.");
3724}
3725
3726static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3727 bool IsPostfixUpdate, const Expr *V,
3728 const Expr *X, const Expr *E,
3729 const Expr *UE, bool IsXLHSInRHSPart,
3730 SourceLocation Loc) {
3731 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3732 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3733 RValue NewVVal;
3734 LValue VLValue = CGF.EmitLValue(V);
3735 LValue XLValue = CGF.EmitLValue(X);
3736 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003737 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3738 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003739 QualType NewVValType;
3740 if (UE) {
3741 // 'x' is updated with some additional value.
3742 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3743 "Update expr in 'atomic capture' must be a binary operator.");
3744 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3745 // Update expressions are allowed to have the following forms:
3746 // x binop= expr; -> xrval + expr;
3747 // x++, ++x -> xrval + 1;
3748 // x--, --x -> xrval - 1;
3749 // x = x binop expr; -> xrval binop expr
3750 // x = expr Op x; - > expr binop xrval;
3751 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3752 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3753 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3754 NewVValType = XRValExpr->getType();
3755 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3756 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003757 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003758 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3759 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3760 RValue Res = CGF.EmitAnyExpr(UE);
3761 NewVVal = IsPostfixUpdate ? XRValue : Res;
3762 return Res;
3763 };
3764 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3765 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3766 if (Res.first) {
3767 // 'atomicrmw' instruction was generated.
3768 if (IsPostfixUpdate) {
3769 // Use old value from 'atomicrmw'.
3770 NewVVal = Res.second;
3771 } else {
3772 // 'atomicrmw' does not provide new value, so evaluate it using old
3773 // value of 'x'.
3774 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3775 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3776 NewVVal = CGF.EmitAnyExpr(UE);
3777 }
3778 }
3779 } else {
3780 // 'x' is simply rewritten with some 'expr'.
3781 NewVValType = X->getType().getNonReferenceType();
3782 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003783 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003784 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003785 NewVVal = XRValue;
3786 return ExprRValue;
3787 };
3788 // Try to perform atomicrmw xchg, otherwise simple exchange.
3789 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3790 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3791 Loc, Gen);
3792 if (Res.first) {
3793 // 'atomicrmw' instruction was generated.
3794 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3795 }
3796 }
3797 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003798 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003799 // OpenMP, 2.12.6, atomic Construct
3800 // Any atomic construct with a seq_cst clause forces the atomically
3801 // performed operation to include an implicit flush operation without a
3802 // list.
3803 if (IsSeqCst)
3804 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3805}
3806
Alexey Bataevb57056f2015-01-22 06:17:56 +00003807static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003808 bool IsSeqCst, bool IsPostfixUpdate,
3809 const Expr *X, const Expr *V, const Expr *E,
3810 const Expr *UE, bool IsXLHSInRHSPart,
3811 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003812 switch (Kind) {
3813 case OMPC_read:
3814 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3815 break;
3816 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003817 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3818 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003819 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003820 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003821 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3822 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003823 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003824 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3825 IsXLHSInRHSPart, Loc);
3826 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003827 case OMPC_if:
3828 case OMPC_final:
3829 case OMPC_num_threads:
3830 case OMPC_private:
3831 case OMPC_firstprivate:
3832 case OMPC_lastprivate:
3833 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003834 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003835 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003836 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003837 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003838 case OMPC_collapse:
3839 case OMPC_default:
3840 case OMPC_seq_cst:
3841 case OMPC_shared:
3842 case OMPC_linear:
3843 case OMPC_aligned:
3844 case OMPC_copyin:
3845 case OMPC_copyprivate:
3846 case OMPC_flush:
3847 case OMPC_proc_bind:
3848 case OMPC_schedule:
3849 case OMPC_ordered:
3850 case OMPC_nowait:
3851 case OMPC_untied:
3852 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003853 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003854 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003855 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003856 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003857 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003858 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003859 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003860 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003861 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003862 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003863 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003864 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003865 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003866 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003867 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003868 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003869 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003870 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003871 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003872 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003873 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3874 }
3875}
3876
3877void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003878 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003879 OpenMPClauseKind Kind = OMPC_unknown;
3880 for (auto *C : S.clauses()) {
3881 // Find first clause (skip seq_cst clause, if it is first).
3882 if (C->getClauseKind() != OMPC_seq_cst) {
3883 Kind = C->getClauseKind();
3884 break;
3885 }
3886 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003887
Alexey Bataev475a7442018-01-12 19:39:11 +00003888 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003889 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003890 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003891 }
3892 // Processing for statements under 'atomic capture'.
3893 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3894 for (const auto *C : Compound->body()) {
3895 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3896 enterFullExpression(EWC);
3897 }
3898 }
3899 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003900
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003901 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3902 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003903 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003904 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3905 S.getV(), S.getExpr(), S.getUpdateExpr(),
3906 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003907 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003908 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003909 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003910}
3911
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003912static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3913 const OMPExecutableDirective &S,
3914 const RegionCodeGenTy &CodeGen) {
3915 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3916 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003917
Samuel Antaoee8fb302016-01-06 13:42:12 +00003918 llvm::Function *Fn = nullptr;
3919 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003920
Samuel Antaobed3c462015-10-02 16:14:20 +00003921 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003922 // Check for the at most one if clause associated with the target region.
3923 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3924 if (C->getNameModifier() == OMPD_unknown ||
3925 C->getNameModifier() == OMPD_target) {
3926 IfCond = C->getCondition();
3927 break;
3928 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003929 }
3930
3931 // Check if we have any device clause associated with the directive.
3932 const Expr *Device = nullptr;
3933 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3934 Device = C->getDevice();
3935 }
3936
Samuel Antaoee8fb302016-01-06 13:42:12 +00003937 // Check if we have an if clause whose conditional always evaluates to false
3938 // or if we do not have any targets specified. If so the target region is not
3939 // an offload entry point.
3940 bool IsOffloadEntry = true;
3941 if (IfCond) {
3942 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003943 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944 IsOffloadEntry = false;
3945 }
3946 if (CGM.getLangOpts().OMPTargetTriples.empty())
3947 IsOffloadEntry = false;
3948
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003949 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003950 StringRef ParentName;
3951 // In case we have Ctors/Dtors we use the complete type variant to produce
3952 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003953 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003954 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003955 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003956 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3957 else
3958 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003959 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003960
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003961 // Emit target region as a standalone region.
3962 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3963 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003964 OMPLexicalScope Scope(CGF, S, OMPD_task);
3965 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003966}
3967
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003968static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3969 PrePostActionTy &Action) {
3970 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3971 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3972 CGF.EmitOMPPrivateClause(S, PrivateScope);
3973 (void)PrivateScope.Privatize();
3974
3975 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003976 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003977}
3978
3979void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3980 StringRef ParentName,
3981 const OMPTargetDirective &S) {
3982 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3983 emitTargetRegion(CGF, S, Action);
3984 };
3985 llvm::Function *Fn;
3986 llvm::Constant *Addr;
3987 // Emit target region as a standalone region.
3988 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3989 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3990 assert(Fn && Addr && "Target device function emission failed.");
3991}
3992
3993void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3994 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3995 emitTargetRegion(CGF, S, Action);
3996 };
3997 emitCommonOMPTargetDirective(*this, S, CodeGen);
3998}
3999
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004000static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4001 const OMPExecutableDirective &S,
4002 OpenMPDirectiveKind InnermostKind,
4003 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004004 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4005 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4006 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004007
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004008 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4009 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004010 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004011 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4012 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004013
Carlo Bertollic6872252016-04-04 15:55:02 +00004014 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4015 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004016 }
4017
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004018 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004019 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4020 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004021 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4022 CapturedVars);
4023}
4024
4025void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004026 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004027 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004028 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004029 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4030 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004031 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004032 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004033 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004034 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004035 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004036 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004037 emitPostUpdateForReductionClause(
4038 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004039}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004040
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004041static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4042 const OMPTargetTeamsDirective &S) {
4043 auto *CS = S.getCapturedStmt(OMPD_teams);
4044 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004045 // Emit teams region as a standalone region.
4046 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4047 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4048 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4049 CGF.EmitOMPPrivateClause(S, PrivateScope);
4050 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4051 (void)PrivateScope.Privatize();
4052 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004053 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004054 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004055 };
4056 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004057 emitPostUpdateForReductionClause(
4058 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004059}
4060
4061void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4062 CodeGenModule &CGM, StringRef ParentName,
4063 const OMPTargetTeamsDirective &S) {
4064 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4065 emitTargetTeamsRegion(CGF, Action, S);
4066 };
4067 llvm::Function *Fn;
4068 llvm::Constant *Addr;
4069 // Emit target region as a standalone region.
4070 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4071 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4072 assert(Fn && Addr && "Target device function emission failed.");
4073}
4074
4075void CodeGenFunction::EmitOMPTargetTeamsDirective(
4076 const OMPTargetTeamsDirective &S) {
4077 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4078 emitTargetTeamsRegion(CGF, Action, S);
4079 };
4080 emitCommonOMPTargetDirective(*this, S, CodeGen);
4081}
4082
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004083static void
4084emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4085 const OMPTargetTeamsDistributeDirective &S) {
4086 Action.Enter(CGF);
4087 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4088 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4089 };
4090
4091 // Emit teams region as a standalone region.
4092 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4093 PrePostActionTy &) {
4094 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4095 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4096 (void)PrivateScope.Privatize();
4097 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4098 CodeGenDistribute);
4099 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4100 };
4101 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4102 emitPostUpdateForReductionClause(CGF, S,
4103 [](CodeGenFunction &) { return nullptr; });
4104}
4105
4106void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4107 CodeGenModule &CGM, StringRef ParentName,
4108 const OMPTargetTeamsDistributeDirective &S) {
4109 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4110 emitTargetTeamsDistributeRegion(CGF, Action, S);
4111 };
4112 llvm::Function *Fn;
4113 llvm::Constant *Addr;
4114 // Emit target region as a standalone region.
4115 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4116 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4117 assert(Fn && Addr && "Target device function emission failed.");
4118}
4119
4120void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4121 const OMPTargetTeamsDistributeDirective &S) {
4122 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4123 emitTargetTeamsDistributeRegion(CGF, Action, S);
4124 };
4125 emitCommonOMPTargetDirective(*this, S, CodeGen);
4126}
4127
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004128static void emitTargetTeamsDistributeSimdRegion(
4129 CodeGenFunction &CGF, PrePostActionTy &Action,
4130 const OMPTargetTeamsDistributeSimdDirective &S) {
4131 Action.Enter(CGF);
4132 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4133 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4134 };
4135
4136 // Emit teams region as a standalone region.
4137 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4138 PrePostActionTy &) {
4139 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4140 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4141 (void)PrivateScope.Privatize();
4142 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4143 CodeGenDistribute);
4144 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4145 };
4146 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4147 emitPostUpdateForReductionClause(CGF, S,
4148 [](CodeGenFunction &) { return nullptr; });
4149}
4150
4151void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4152 CodeGenModule &CGM, StringRef ParentName,
4153 const OMPTargetTeamsDistributeSimdDirective &S) {
4154 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4155 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4156 };
4157 llvm::Function *Fn;
4158 llvm::Constant *Addr;
4159 // Emit target region as a standalone region.
4160 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4161 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4162 assert(Fn && Addr && "Target device function emission failed.");
4163}
4164
4165void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4166 const OMPTargetTeamsDistributeSimdDirective &S) {
4167 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4168 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4169 };
4170 emitCommonOMPTargetDirective(*this, S, CodeGen);
4171}
4172
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004173void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4174 const OMPTeamsDistributeDirective &S) {
4175
4176 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4177 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4178 };
4179
4180 // Emit teams region as a standalone region.
4181 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4182 PrePostActionTy &) {
4183 OMPPrivateScope PrivateScope(CGF);
4184 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4185 (void)PrivateScope.Privatize();
4186 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4187 CodeGenDistribute);
4188 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4189 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004190 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004191 emitPostUpdateForReductionClause(*this, S,
4192 [](CodeGenFunction &) { return nullptr; });
4193}
4194
Alexey Bataev999277a2017-12-06 14:31:09 +00004195void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4196 const OMPTeamsDistributeSimdDirective &S) {
4197 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4198 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4199 };
4200
4201 // Emit teams region as a standalone region.
4202 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4203 PrePostActionTy &) {
4204 OMPPrivateScope PrivateScope(CGF);
4205 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4206 (void)PrivateScope.Privatize();
4207 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4208 CodeGenDistribute);
4209 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4210 };
4211 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4212 emitPostUpdateForReductionClause(*this, S,
4213 [](CodeGenFunction &) { return nullptr; });
4214}
4215
Carlo Bertolli62fae152017-11-20 20:46:39 +00004216void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4217 const OMPTeamsDistributeParallelForDirective &S) {
4218 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4219 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4220 S.getDistInc());
4221 };
4222
4223 // Emit teams region as a standalone region.
4224 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4225 PrePostActionTy &) {
4226 OMPPrivateScope PrivateScope(CGF);
4227 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4228 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004229 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4230 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004231 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4232 };
4233 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4234 emitPostUpdateForReductionClause(*this, S,
4235 [](CodeGenFunction &) { return nullptr; });
4236}
4237
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004238void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4239 const OMPTeamsDistributeParallelForSimdDirective &S) {
4240 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4241 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4242 S.getDistInc());
4243 };
4244
4245 // Emit teams region as a standalone region.
4246 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4247 PrePostActionTy &) {
4248 OMPPrivateScope PrivateScope(CGF);
4249 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4250 (void)PrivateScope.Privatize();
4251 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4252 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4253 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4254 };
4255 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4256 emitPostUpdateForReductionClause(*this, S,
4257 [](CodeGenFunction &) { return nullptr; });
4258}
4259
Carlo Bertolli52978c32018-01-03 21:12:44 +00004260static void emitTargetTeamsDistributeParallelForRegion(
4261 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4262 PrePostActionTy &Action) {
4263 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4264 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4265 S.getDistInc());
4266 };
4267
4268 // Emit teams region as a standalone region.
4269 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4270 PrePostActionTy &) {
4271 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4272 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4273 (void)PrivateScope.Privatize();
4274 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4275 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4276 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4277 };
4278
4279 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4280 CodeGenTeams);
4281 emitPostUpdateForReductionClause(CGF, S,
4282 [](CodeGenFunction &) { return nullptr; });
4283}
4284
4285void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4286 CodeGenModule &CGM, StringRef ParentName,
4287 const OMPTargetTeamsDistributeParallelForDirective &S) {
4288 // Emit SPMD target teams distribute parallel for region as a standalone
4289 // region.
4290 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4291 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4292 };
4293 llvm::Function *Fn;
4294 llvm::Constant *Addr;
4295 // Emit target region as a standalone region.
4296 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4297 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4298 assert(Fn && Addr && "Target device function emission failed.");
4299}
4300
4301void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4302 const OMPTargetTeamsDistributeParallelForDirective &S) {
4303 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4304 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4305 };
4306 emitCommonOMPTargetDirective(*this, S, CodeGen);
4307}
4308
Alexey Bataev647dd842018-01-15 20:59:40 +00004309static void emitTargetTeamsDistributeParallelForSimdRegion(
4310 CodeGenFunction &CGF,
4311 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4312 PrePostActionTy &Action) {
4313 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}