blob: 07c1e3aa5150543140d4065c580849d9da2f807b [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 Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
Alexey Bataev6a71f362017-08-22 17:54:52 +000068 assert(VD == VD->getCanonicalDecl() &&
69 "Canonical decl must be captured.");
Alexey Bataev4ba78a42016-04-27 07:56:03 +000070 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71 isCapturedVar(CGF, VD) ||
72 (CGF.CapturedStmtInfo &&
73 InlinedShareds.isGlobalVarCaptured(VD)),
74 VD->getType().getNonReferenceType(), VK_LValue,
75 SourceLocation());
76 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77 return CGF.EmitLValue(&DRE).getAddress();
78 });
79 }
80 }
81 (void)InlinedShareds.Privatize();
82 }
83 }
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99 : OMPLexicalScope(CGF, S,
100 /*AsInlined=*/false,
101 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
102};
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)
115 : OMPLexicalScope(CGF, S,
116 /*AsInlined=*/false,
117 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
118};
119
Alexey Bataev5a3af132016-03-29 08:58:54 +0000120/// Private scope for OpenMP loop-based directives, that supports capturing
121/// of used expression from loop statement.
122class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000124 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 for (auto *E : S.counters()) {
126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
128 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
129 });
130 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000131 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000132 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
133 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
134 for (const auto *I : PreInits->decls())
135 CGF.EmitVarDecl(cast<VarDecl>(*I));
136 }
137 }
138 }
139
140public:
141 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
142 : CodeGenFunction::RunCleanupsScope(CGF) {
143 emitPreInitStmt(CGF, S);
144 }
145};
146
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000147class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
148 CodeGenFunction::OMPPrivateScope InlinedShareds;
149
150 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
151 return CGF.LambdaCaptureFields.lookup(VD) ||
152 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
153 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
154 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
155 }
156
157public:
158 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
159 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
160 InlinedShareds(CGF) {
161 for (const auto *C : S.clauses()) {
162 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
163 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
164 for (const auto *I : PreInit->decls()) {
165 if (!I->hasAttr<OMPCaptureNoInitAttr>())
166 CGF.EmitVarDecl(cast<VarDecl>(*I));
167 else {
168 CodeGenFunction::AutoVarEmission Emission =
169 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
170 CGF.EmitAutoVarCleanups(Emission);
171 }
172 }
173 }
174 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
175 for (const Expr *E : UDP->varlists()) {
176 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
177 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
178 CGF.EmitVarDecl(*OED);
179 }
180 }
181 }
182 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
183 CGF.EmitOMPPrivateClause(S, InlinedShareds);
184 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
185 if (const Expr *E = TG->getReductionRef())
186 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
187 }
188 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
189 while (CS) {
190 for (auto &C : CS->captures()) {
191 if (C.capturesVariable() || C.capturesVariableByCopy()) {
192 auto *VD = C.getCapturedVar();
193 assert(VD == VD->getCanonicalDecl() &&
194 "Canonical decl must be captured.");
195 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
196 isCapturedVar(CGF, VD) ||
197 (CGF.CapturedStmtInfo &&
198 InlinedShareds.isGlobalVarCaptured(VD)),
199 VD->getType().getNonReferenceType(), VK_LValue,
200 SourceLocation());
201 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
202 return CGF.EmitLValue(&DRE).getAddress();
203 });
204 }
205 }
206 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
207 }
208 (void)InlinedShareds.Privatize();
209 }
210};
211
Alexey Bataev3392d762016-02-16 11:18:12 +0000212} // namespace
213
Alexey Bataevf8365372017-11-17 17:57:25 +0000214static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
215 const OMPExecutableDirective &S,
216 const RegionCodeGenTy &CodeGen);
217
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000218LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
219 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
220 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
221 OrigVD = OrigVD->getCanonicalDecl();
222 bool IsCaptured =
223 LambdaCaptureFields.lookup(OrigVD) ||
224 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
225 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
226 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
227 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
228 return EmitLValue(&DRE);
229 }
230 }
231 return EmitLValue(E);
232}
233
Alexey Bataev1189bd02016-01-26 12:20:39 +0000234llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
235 auto &C = getContext();
236 llvm::Value *Size = nullptr;
237 auto SizeInChars = C.getTypeSizeInChars(Ty);
238 if (SizeInChars.isZero()) {
239 // getTypeSizeInChars() returns 0 for a VLA.
240 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
241 llvm::Value *ArraySize;
242 std::tie(ArraySize, Ty) = getVLASize(VAT);
243 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
244 }
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()) {
269 llvm::Value *CV =
270 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
271
272 // If the field is not a pointer, we need to save the actual value
273 // and load it as a void pointer.
274 if (!CurField->getType()->isAnyPointerType()) {
275 auto &Ctx = getContext();
276 auto DstAddr = CreateMemTemp(
277 Ctx.getUIntPtrType(),
278 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
279 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
280
281 auto *SrcAddrVal = EmitScalarConversion(
282 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
283 Ctx.getPointerType(CurField->getType()), SourceLocation());
284 LValue SrcLV =
285 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
286
287 // Store the value using the source type pointer.
288 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
289
290 // Load the value using the destination type pointer.
291 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
292 }
293 CapturedVars.push_back(CV);
294 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000295 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000296 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000297 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000298 }
299}
300
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000301static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
302 StringRef Name, LValue AddrLV,
303 bool isReferenceType = false) {
304 ASTContext &Ctx = CGF.getContext();
305
306 auto *CastedPtr = CGF.EmitScalarConversion(
307 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
308 Ctx.getPointerType(DstType), SourceLocation());
309 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) {
499 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
500 Args[Cnt]->getName(),
501 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000502 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000503 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000504 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000505 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000506 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000507 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000508 } else if (I->capturesVariable()) {
509 auto *Var = I->getCapturedVar();
510 QualType VarTy = Var->getType();
511 Address ArgAddr = ArgLVal.getAddress();
512 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000513 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000514 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000515 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000516 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000517 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000518 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
519 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000520 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000521 if (!FO.RegisterCastedArgsOnly) {
522 LocalAddrs.insert(
523 {Args[Cnt],
524 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
525 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000526 } else if (I->capturesVariableByCopy()) {
527 assert(!FD->getType()->isAnyPointerType() &&
528 "Not expecting a captured pointer.");
529 auto *Var = I->getCapturedVar();
530 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000531 LocalAddrs.insert(
532 {Args[Cnt],
533 {Var,
534 FO.UIntPtrCastRequired
535 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
536 ArgLVal, VarTy->isReferenceType())
537 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000538 } else {
539 // If 'this' is captured, load it into CXXThisValue.
540 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000541 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
542 .getScalarVal();
543 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000544 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000545 ++Cnt;
546 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000547 }
548
Alexey Bataeve754b182017-08-09 19:38:53 +0000549 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000550}
551
552llvm::Function *
553CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
554 assert(
555 CapturedStmtInfo &&
556 "CapturedStmtInfo should be set when generating the captured function");
557 const CapturedDecl *CD = S.getCapturedDecl();
558 // Build the argument list.
559 bool NeedWrapperFunction =
560 getDebugInfo() &&
561 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
562 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000563 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000564 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000565 SmallString<256> Buffer;
566 llvm::raw_svector_ostream Out(Buffer);
567 Out << CapturedStmtInfo->getHelperName();
568 if (NeedWrapperFunction)
569 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000570 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000571 Out.str());
572 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
573 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000574 for (const auto &LocalAddrPair : LocalAddrs) {
575 if (LocalAddrPair.second.first) {
576 setAddrOfLocalVar(LocalAddrPair.second.first,
577 LocalAddrPair.second.second);
578 }
579 }
580 for (const auto &VLASizePair : VLASizes)
581 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000582 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000583 CapturedStmtInfo->EmitBody(*this, CD->getBody());
584 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000585 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000586 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000587
Alexey Bataevefd884d2017-08-04 21:26:25 +0000588 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000589 /*RegisterCastedArgsOnly=*/true,
590 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000591 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000592 Args.clear();
593 LocalAddrs.clear();
594 VLASizes.clear();
595 llvm::Function *WrapperF =
596 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000597 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000598 llvm::SmallVector<llvm::Value *, 4> CallArgs;
599 for (const auto *Arg : Args) {
600 llvm::Value *CallArg;
601 auto I = LocalAddrs.find(Arg);
602 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000603 LValue LV = WrapperCGF.MakeAddrLValue(
604 I->second.second,
605 I->second.first ? I->second.first->getType() : Arg->getType(),
606 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000607 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
608 } else {
609 auto EI = VLASizes.find(Arg);
610 if (EI != VLASizes.end())
611 CallArg = EI->second.second;
612 else {
613 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000614 Arg->getType(),
615 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000616 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
617 }
618 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000619 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000621 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
622 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000623 WrapperCGF.FinishFunction();
624 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000625}
626
Alexey Bataev9959db52014-05-06 10:08:46 +0000627//===----------------------------------------------------------------------===//
628// OpenMP Directive Emission
629//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000631 Address DestAddr, Address SrcAddr, QualType OriginalType,
632 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000633 // Perform element-by-element initialization.
634 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000635
636 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000637 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000638 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
639 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
640
641 auto SrcBegin = SrcAddr.getPointer();
642 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000644 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
645 // The basic structure here is a while-do loop.
646 auto BodyBB = createBasicBlock("omp.arraycpy.body");
647 auto DoneBB = createBasicBlock("omp.arraycpy.done");
648 auto IsEmpty =
649 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
650 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000651
Alexey Bataev420d45b2015-04-14 05:11:24 +0000652 // Enter the loop body, making that address the current address.
653 auto EntryBB = Builder.GetInsertBlock();
654 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000655
656 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
657
658 llvm::PHINode *SrcElementPHI =
659 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
660 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
661 Address SrcElementCurrent =
662 Address(SrcElementPHI,
663 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
664
665 llvm::PHINode *DestElementPHI =
666 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
667 DestElementPHI->addIncoming(DestBegin, EntryBB);
668 Address DestElementCurrent =
669 Address(DestElementPHI,
670 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000671
Alexey Bataev420d45b2015-04-14 05:11:24 +0000672 // Emit copy.
673 CopyGen(DestElementCurrent, SrcElementCurrent);
674
675 // Shift the address forward by one element.
676 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000677 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000678 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000679 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000680 // Check whether we've reached the end.
681 auto Done =
682 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
683 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000684 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
685 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000686
687 // Done.
688 EmitBlock(DoneBB, /*IsFinished=*/true);
689}
690
John McCall7f416cc2015-09-08 08:05:57 +0000691void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
692 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000693 const VarDecl *SrcVD, const Expr *Copy) {
694 if (OriginalType->isArrayType()) {
695 auto *BO = dyn_cast<BinaryOperator>(Copy);
696 if (BO && BO->getOpcode() == BO_Assign) {
697 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000698 EmitAggregateAssign(DestAddr, SrcAddr, 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 Bataev9afe5752016-05-24 07:40:12 +0000741 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000742 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000743 auto IRef = C->varlist_begin();
744 auto InitsRef = C->inits().begin();
745 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000746 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000747 bool ThisFirstprivateIsLastprivate =
748 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000749 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000750 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000751 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752 !FD->getType()->isReferenceType()) {
753 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
754 ++IRef;
755 ++InitsRef;
756 continue;
757 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000758 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000759 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000760 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000761 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
762 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
763 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000764 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
765 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
766 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000767 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000768 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000769 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000770 // Emit VarDecl with copy init for arrays.
771 // Get the address of the original variable captured in current
772 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000773 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000774 auto Emission = EmitAutoVarAlloca(*VD);
775 auto *Init = VD->getInit();
776 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
777 // Perform simple memcpy.
778 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000779 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000780 } else {
781 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000782 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000783 [this, VDInit, Init](Address DestElement,
784 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000785 // Clean up any temporaries needed by the initialization.
786 RunCleanupsScope InitScope(*this);
787 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000788 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000789 EmitAnyExprToMem(Init, DestElement,
790 Init->getType().getQualifiers(),
791 /*IsInitializer*/ false);
792 LocalDeclMap.erase(VDInit);
793 });
794 }
795 EmitAutoVarCleanups(Emission);
796 return Emission.getAllocatedAddress();
797 });
798 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000799 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000800 // Emit private VarDecl with copy init.
801 // Remap temp VDInit variable to the address of the original
802 // variable
803 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000804 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000805 EmitDecl(*VD);
806 LocalDeclMap.erase(VDInit);
807 return GetAddrOfLocalVar(VD);
808 });
809 }
810 assert(IsRegistered &&
811 "firstprivate var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000815 ++IRef;
816 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000817 }
818 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000819 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000820}
821
Alexey Bataev03b340a2014-10-21 03:16:40 +0000822void CodeGenFunction::EmitOMPPrivateClause(
823 const OMPExecutableDirective &D,
824 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000825 if (!HaveInsertPoint())
826 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000827 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000828 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000829 auto IRef = C->varlist_begin();
830 for (auto IInit : C->private_copies()) {
831 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000832 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
833 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
834 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000835 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000836 // Emit private VarDecl with copy init.
837 EmitDecl(*VD);
838 return GetAddrOfLocalVar(VD);
839 });
840 assert(IsRegistered && "private var already registered as private");
841 // Silence the warning about unused variable.
842 (void)IsRegistered;
843 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000844 ++IRef;
845 }
846 }
847}
848
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000849bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000850 if (!HaveInsertPoint())
851 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000852 // threadprivate_var1 = master_threadprivate_var1;
853 // operator=(threadprivate_var2, master_threadprivate_var2);
854 // ...
855 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000856 llvm::DenseSet<const VarDecl *> CopiedVars;
857 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000858 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000859 auto IRef = C->varlist_begin();
860 auto ISrcRef = C->source_exprs().begin();
861 auto IDestRef = C->destination_exprs().begin();
862 for (auto *AssignOp : C->assignment_ops()) {
863 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000864 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000865 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000866 // Get the address of the master variable. If we are emitting code with
867 // TLS support, the address is passed from the master as field in the
868 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000869 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000870 if (getLangOpts().OpenMPUseTLS &&
871 getContext().getTargetInfo().isTLSSupported()) {
872 assert(CapturedStmtInfo->lookup(VD) &&
873 "Copyin threadprivates should have been captured!");
874 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
875 VK_LValue, (*IRef)->getExprLoc());
876 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000877 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000878 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000879 MasterAddr =
880 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
881 : CGM.GetAddrOfGlobal(VD),
882 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000883 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000884 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000885 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000886 if (CopiedVars.size() == 1) {
887 // At first check if current thread is a master thread. If it is, no
888 // need to copy data.
889 CopyBegin = createBasicBlock("copyin.not.master");
890 CopyEnd = createBasicBlock("copyin.not.master.end");
891 Builder.CreateCondBr(
892 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000893 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
894 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000895 CopyBegin, CopyEnd);
896 EmitBlock(CopyBegin);
897 }
898 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
899 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000900 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000901 }
902 ++IRef;
903 ++ISrcRef;
904 ++IDestRef;
905 }
906 }
907 if (CopyEnd) {
908 // Exit out of copying procedure for non-master thread.
909 EmitBlock(CopyEnd, /*IsFinished=*/true);
910 return true;
911 }
912 return false;
913}
914
Alexey Bataev38e89532015-04-16 04:54:05 +0000915bool CodeGenFunction::EmitOMPLastprivateClauseInit(
916 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000917 if (!HaveInsertPoint())
918 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000919 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000920 llvm::DenseSet<const VarDecl *> SIMDLCVs;
921 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
922 auto *LoopDirective = cast<OMPLoopDirective>(&D);
923 for (auto *C : LoopDirective->counters()) {
924 SIMDLCVs.insert(
925 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
926 }
927 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000928 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000929 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000930 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000931 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
932 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000933 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000934 auto IRef = C->varlist_begin();
935 auto IDestRef = C->destination_exprs().begin();
936 for (auto *IInit : C->private_copies()) {
937 // Keep the address of the original variable for future update at the end
938 // of the loop.
939 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000940 // Taskloops do not require additional initialization, it is done in
941 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000942 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
943 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000944 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000945 DeclRefExpr DRE(
946 const_cast<VarDecl *>(OrigVD),
947 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
948 OrigVD) != nullptr,
949 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
950 return EmitLValue(&DRE).getAddress();
951 });
952 // Check if the variable is also a firstprivate: in this case IInit is
953 // not generated. Initialization of this variable will happen in codegen
954 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000955 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000956 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000957 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
958 // Emit private VarDecl with copy init.
959 EmitDecl(*VD);
960 return GetAddrOfLocalVar(VD);
961 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000962 assert(IsRegistered &&
963 "lastprivate var already registered as private");
964 (void)IsRegistered;
965 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000966 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000967 ++IRef;
968 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000969 }
970 }
971 return HasAtLeastOneLastprivate;
972}
973
974void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000975 const OMPExecutableDirective &D, bool NoFinals,
976 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000977 if (!HaveInsertPoint())
978 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000979 // Emit following code:
980 // if (<IsLastIterCond>) {
981 // orig_var1 = private_orig_var1;
982 // ...
983 // orig_varn = private_orig_varn;
984 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000985 llvm::BasicBlock *ThenBB = nullptr;
986 llvm::BasicBlock *DoneBB = nullptr;
987 if (IsLastIterCond) {
988 ThenBB = createBasicBlock(".omp.lastprivate.then");
989 DoneBB = createBasicBlock(".omp.lastprivate.done");
990 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
991 EmitBlock(ThenBB);
992 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000993 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
994 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000995 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000996 auto IC = LoopDirective->counters().begin();
997 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000998 auto *D =
999 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1000 if (NoFinals)
1001 AlreadyEmittedVars.insert(D);
1002 else
1003 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001004 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001005 }
1006 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001007 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1008 auto IRef = C->varlist_begin();
1009 auto ISrcRef = C->source_exprs().begin();
1010 auto IDestRef = C->destination_exprs().begin();
1011 for (auto *AssignOp : C->assignment_ops()) {
1012 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1013 QualType Type = PrivateVD->getType();
1014 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1015 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1016 // If lastprivate variable is a loop control variable for loop-based
1017 // directive, update its value before copyin back to original
1018 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001019 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1020 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001021 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1022 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1023 // Get the address of the original variable.
1024 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1025 // Get the address of the private variable.
1026 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1027 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1028 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001029 Address(Builder.CreateLoad(PrivateAddr),
1030 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001031 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001032 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001033 ++IRef;
1034 ++ISrcRef;
1035 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001036 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001037 if (auto *PostUpdate = C->getPostUpdateExpr())
1038 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001040 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001041 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001042}
1043
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001044void CodeGenFunction::EmitOMPReductionClauseInit(
1045 const OMPExecutableDirective &D,
1046 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001047 if (!HaveInsertPoint())
1048 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001049 SmallVector<const Expr *, 4> Shareds;
1050 SmallVector<const Expr *, 4> Privates;
1051 SmallVector<const Expr *, 4> ReductionOps;
1052 SmallVector<const Expr *, 4> LHSs;
1053 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001054 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001055 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001056 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001057 auto ILHS = C->lhs_exprs().begin();
1058 auto IRHS = C->rhs_exprs().begin();
1059 for (const auto *Ref : C->varlists()) {
1060 Shareds.emplace_back(Ref);
1061 Privates.emplace_back(*IPriv);
1062 ReductionOps.emplace_back(*IRed);
1063 LHSs.emplace_back(*ILHS);
1064 RHSs.emplace_back(*IRHS);
1065 std::advance(IPriv, 1);
1066 std::advance(IRed, 1);
1067 std::advance(ILHS, 1);
1068 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001069 }
1070 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001071 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1072 unsigned Count = 0;
1073 auto ILHS = LHSs.begin();
1074 auto IRHS = RHSs.begin();
1075 auto IPriv = Privates.begin();
1076 for (const auto *IRef : Shareds) {
1077 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1078 // Emit private VarDecl with reduction init.
1079 RedCG.emitSharedLValue(*this, Count);
1080 RedCG.emitAggregateType(*this, Count);
1081 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1082 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1083 RedCG.getSharedLValue(Count),
1084 [&Emission](CodeGenFunction &CGF) {
1085 CGF.EmitAutoVarInit(Emission);
1086 return true;
1087 });
1088 EmitAutoVarCleanups(Emission);
1089 Address BaseAddr = RedCG.adjustPrivateAddress(
1090 *this, Count, Emission.getAllocatedAddress());
1091 bool IsRegistered = PrivateScope.addPrivate(
1092 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1093 assert(IsRegistered && "private var already registered as private");
1094 // Silence the warning about unused variable.
1095 (void)IsRegistered;
1096
1097 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1098 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001099 QualType Type = PrivateVD->getType();
1100 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1101 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001102 // Store the address of the original variable associated with the LHS
1103 // implicit variable.
1104 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1105 return RedCG.getSharedLValue(Count).getAddress();
1106 });
1107 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1108 return GetAddrOfLocalVar(PrivateVD);
1109 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001110 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1111 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001112 // Store the address of the original variable associated with the LHS
1113 // implicit variable.
1114 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1115 return RedCG.getSharedLValue(Count).getAddress();
1116 });
1117 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1118 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1119 ConvertTypeForMem(RHSVD->getType()),
1120 "rhs.begin");
1121 });
1122 } else {
1123 QualType Type = PrivateVD->getType();
1124 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1125 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1126 // Store the address of the original variable associated with the LHS
1127 // implicit variable.
1128 if (IsArray) {
1129 OriginalAddr = Builder.CreateElementBitCast(
1130 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1131 }
1132 PrivateScope.addPrivate(
1133 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1134 PrivateScope.addPrivate(
1135 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1136 return IsArray
1137 ? Builder.CreateElementBitCast(
1138 GetAddrOfLocalVar(PrivateVD),
1139 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1140 : GetAddrOfLocalVar(PrivateVD);
1141 });
1142 }
1143 ++ILHS;
1144 ++IRHS;
1145 ++IPriv;
1146 ++Count;
1147 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001148}
1149
1150void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001151 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001152 if (!HaveInsertPoint())
1153 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001154 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001155 llvm::SmallVector<const Expr *, 8> LHSExprs;
1156 llvm::SmallVector<const Expr *, 8> RHSExprs;
1157 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001159 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001160 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001161 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001162 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1163 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1164 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1165 }
1166 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001167 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1168 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001169 ReductionKind == OMPD_simd;
1170 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001171 // Emit nowait reduction if nowait clause is present or directive is a
1172 // parallel directive (it always has implicit barrier).
1173 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001174 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001175 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001176 }
1177}
1178
Alexey Bataev61205072016-03-02 04:57:40 +00001179static void emitPostUpdateForReductionClause(
1180 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1181 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1182 if (!CGF.HaveInsertPoint())
1183 return;
1184 llvm::BasicBlock *DoneBB = nullptr;
1185 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1186 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1187 if (!DoneBB) {
1188 if (auto *Cond = CondGen(CGF)) {
1189 // If the first post-update expression is found, emit conditional
1190 // block if it was requested.
1191 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1192 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1193 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1194 CGF.EmitBlock(ThenBB);
1195 }
1196 }
1197 CGF.EmitIgnoredExpr(PostUpdate);
1198 }
1199 }
1200 if (DoneBB)
1201 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1202}
1203
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001204namespace {
1205/// Codegen lambda for appending distribute lower and upper bounds to outlined
1206/// parallel function. This is necessary for combined constructs such as
1207/// 'distribute parallel for'
1208typedef llvm::function_ref<void(CodeGenFunction &,
1209 const OMPExecutableDirective &,
1210 llvm::SmallVectorImpl<llvm::Value *> &)>
1211 CodeGenBoundParametersTy;
1212} // anonymous namespace
1213
1214static void emitCommonOMPParallelDirective(
1215 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1216 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1217 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001218 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1219 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1220 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001221 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001222 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001223 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1224 /*IgnoreResultAssign*/ true);
1225 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1226 CGF, NumThreads, NumThreadsClause->getLocStart());
1227 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001228 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001229 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001230 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1231 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1232 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001233 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001234 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1235 if (C->getNameModifier() == OMPD_unknown ||
1236 C->getNameModifier() == OMPD_parallel) {
1237 IfCond = C->getCondition();
1238 break;
1239 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001240 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001241
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001242 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001243 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001244 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1245 // lower and upper bounds with the pragma 'for' chunking mechanism.
1246 // The following lambda takes care of appending the lower and upper bound
1247 // parameters when necessary
1248 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001249 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001250 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001251 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001252}
1253
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001254static void emitEmptyBoundParameters(CodeGenFunction &,
1255 const OMPExecutableDirective &,
1256 llvm::SmallVectorImpl<llvm::Value *> &) {}
1257
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001258void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001259 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001260 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001261 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001262 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001263 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1264 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001265 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001266 // propagation master's thread values of threadprivate variables to local
1267 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001268 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1269 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1270 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001271 }
1272 CGF.EmitOMPPrivateClause(S, PrivateScope);
1273 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1274 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001275 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001276 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001277 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001278 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1279 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001280 emitPostUpdateForReductionClause(
1281 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001282}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001283
Alexey Bataev0f34da12015-07-02 04:17:07 +00001284void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1285 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001286 RunCleanupsScope BodyScope(*this);
1287 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001288 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001289 EmitIgnoredExpr(I);
1290 }
Alexander Musman3276a272015-03-21 10:12:56 +00001291 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001292 // In distribute directives only loop counters may be marked as linear, no
1293 // need to generate the code for them.
1294 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1295 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1296 for (auto *U : C->updates())
1297 EmitIgnoredExpr(U);
1298 }
Alexander Musman3276a272015-03-21 10:12:56 +00001299 }
1300
Alexander Musmana5f070a2014-10-01 06:03:56 +00001301 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001302 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001303 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001304 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001305 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306 // The end (updates/cleanups).
1307 EmitBlock(Continue.getBlock());
1308 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309}
1310
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001311void CodeGenFunction::EmitOMPInnerLoop(
1312 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1313 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001314 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1315 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001316 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001317
1318 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001319 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001320 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001321 const SourceRange &R = S.getSourceRange();
1322 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1323 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001324
1325 // If there are any cleanups between here and the loop-exit scope,
1326 // create a block to stage a loop exit along.
1327 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001328 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001329 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001330
Alexander Musmand196ef22014-10-07 08:57:09 +00001331 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001332
Alexey Bataev2df54a02015-03-12 08:53:29 +00001333 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001334 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335 if (ExitBlock != LoopExit.getBlock()) {
1336 EmitBlock(ExitBlock);
1337 EmitBranchThroughCleanup(LoopExit);
1338 }
1339
1340 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001341 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001342
1343 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001344 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001345 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1346
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001347 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348
1349 // Emit "IV = IV + 1" and a back-edge to the condition block.
1350 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001351 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001352 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353 BreakContinueStack.pop_back();
1354 EmitBranch(CondBlock);
1355 LoopStack.pop();
1356 // Emit the fall-through block.
1357 EmitBlock(LoopExit.getBlock());
1358}
1359
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001360bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001361 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001362 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001363 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001364 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001365 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001366 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001369 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1370 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1371 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1372 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1373 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1374 VD->getInit()->getType(), VK_LValue,
1375 VD->getInit()->getExprLoc());
1376 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1377 VD->getType()),
1378 /*capturedByInit=*/false);
1379 EmitAutoVarCleanups(Emission);
1380 } else
1381 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001382 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001383 // Emit the linear steps for the linear clauses.
1384 // If a step is not constant, it is pre-calculated before the loop.
1385 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1386 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001387 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001388 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001389 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001390 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001391 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001392 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393}
1394
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001395void CodeGenFunction::EmitOMPLinearClauseFinal(
1396 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001397 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001399 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001400 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001401 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001402 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001403 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001404 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001405 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001406 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001407 // If the first post-update expression is found, emit conditional
1408 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1410 DoneBB = createBasicBlock(".omp.linear.pu.done");
1411 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1412 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001413 }
1414 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001415 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1416 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001417 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001419 Address OrigAddr = EmitLValue(&DRE).getAddress();
1420 CodeGenFunction::OMPPrivateScope VarScope(*this);
1421 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001422 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001423 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001424 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001425 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001426 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001427 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001428 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001429 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001430 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001431}
1432
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001433static void emitAlignedClause(CodeGenFunction &CGF,
1434 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001435 if (!CGF.HaveInsertPoint())
1436 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001437 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001438 unsigned ClauseAlignment = 0;
1439 if (auto AlignmentExpr = Clause->getAlignment()) {
1440 auto AlignmentCI =
1441 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1442 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001443 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001444 for (auto E : Clause->varlists()) {
1445 unsigned Alignment = ClauseAlignment;
1446 if (Alignment == 0) {
1447 // OpenMP [2.8.1, Description]
1448 // If no optional parameter is specified, implementation-defined default
1449 // alignments for SIMD instructions on the target platforms are assumed.
1450 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001451 CGF.getContext()
1452 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1453 E->getType()->getPointeeType()))
1454 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001455 }
1456 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1457 "alignment is not power of 2");
1458 if (Alignment != 0) {
1459 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1460 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1461 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001462 }
1463 }
1464}
1465
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001466void CodeGenFunction::EmitOMPPrivateLoopCounters(
1467 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1468 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001469 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001470 auto I = S.private_counters().begin();
1471 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001472 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1473 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001474 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001475 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001476 if (!LocalDeclMap.count(PrivateVD)) {
1477 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1478 EmitAutoVarCleanups(VarEmission);
1479 }
1480 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1481 /*RefersToEnclosingVariableOrCapture=*/false,
1482 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1483 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001484 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001485 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1486 VD->hasGlobalStorage()) {
1487 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1488 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1489 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1490 E->getType(), VK_LValue, E->getExprLoc());
1491 return EmitLValue(&DRE).getAddress();
1492 });
1493 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001494 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001495 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001496}
1497
Alexey Bataev62dbb972015-04-22 11:59:37 +00001498static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1499 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1500 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001501 if (!CGF.HaveInsertPoint())
1502 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001503 {
1504 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001505 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001506 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001507 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001508 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001509 CGF.EmitIgnoredExpr(I);
1510 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001511 }
1512 // Check that loop is executed at least one time.
1513 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1514}
1515
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001516void CodeGenFunction::EmitOMPLinearClause(
1517 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1518 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001519 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001520 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1521 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1522 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1523 for (auto *C : LoopDirective->counters()) {
1524 SIMDLCVs.insert(
1525 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1526 }
1527 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001528 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001529 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001530 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001531 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1532 auto *PrivateVD =
1533 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001534 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1535 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1536 // Emit private VarDecl with copy init.
1537 EmitVarDecl(*PrivateVD);
1538 return GetAddrOfLocalVar(PrivateVD);
1539 });
1540 assert(IsRegistered && "linear var already registered as private");
1541 // Silence the warning about unused variable.
1542 (void)IsRegistered;
1543 } else
1544 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001545 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001546 }
1547 }
1548}
1549
Alexey Bataev45bfad52015-08-21 12:19:04 +00001550static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001551 const OMPExecutableDirective &D,
1552 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001553 if (!CGF.HaveInsertPoint())
1554 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001555 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001556 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1557 /*ignoreResult=*/true);
1558 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1559 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1560 // In presence of finite 'safelen', it may be unsafe to mark all
1561 // the memory instructions parallel, because loop-carried
1562 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001563 if (!IsMonotonic)
1564 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001565 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001566 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1567 /*ignoreResult=*/true);
1568 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001569 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001570 // In presence of finite 'safelen', it may be unsafe to mark all
1571 // the memory instructions parallel, because loop-carried
1572 // dependences of 'safelen' iterations are possible.
1573 CGF.LoopStack.setParallel(false);
1574 }
1575}
1576
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001577void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1578 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001579 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001580 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001581 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001582 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001583}
1584
Alexey Bataevef549a82016-03-09 09:49:09 +00001585void CodeGenFunction::EmitOMPSimdFinal(
1586 const OMPLoopDirective &D,
1587 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001588 if (!HaveInsertPoint())
1589 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001590 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001591 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001592 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001593 for (auto F : D.finals()) {
1594 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001595 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1596 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1597 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1598 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001599 if (!DoneBB) {
1600 if (auto *Cond = CondGen(*this)) {
1601 // If the first post-update expression is found, emit conditional
1602 // block if it was requested.
1603 auto *ThenBB = createBasicBlock(".omp.final.then");
1604 DoneBB = createBasicBlock(".omp.final.done");
1605 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1606 EmitBlock(ThenBB);
1607 }
1608 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001609 Address OrigAddr = Address::invalid();
1610 if (CED)
1611 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1612 else {
1613 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1614 /*RefersToEnclosingVariableOrCapture=*/false,
1615 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1616 OrigAddr = EmitLValue(&DRE).getAddress();
1617 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001618 OMPPrivateScope VarScope(*this);
1619 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001620 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001621 (void)VarScope.Privatize();
1622 EmitIgnoredExpr(F);
1623 }
1624 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001625 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001626 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001627 if (DoneBB)
1628 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001629}
1630
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001631static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1632 const OMPLoopDirective &S,
1633 CodeGenFunction::JumpDest LoopExit) {
1634 CGF.EmitOMPLoopBody(S, LoopExit);
1635 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001636}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001637
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001638/// Emit a helper variable and return corresponding lvalue.
1639static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1640 const DeclRefExpr *Helper) {
1641 auto VDecl = cast<VarDecl>(Helper->getDecl());
1642 CGF.EmitVarDecl(*VDecl);
1643 return CGF.EmitLValue(Helper);
1644}
1645
Alexey Bataevf8365372017-11-17 17:57:25 +00001646static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1647 PrePostActionTy &Action) {
1648 Action.Enter(CGF);
1649 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1650 "Expected simd directive");
1651 OMPLoopScope PreInitScope(CGF, S);
1652 // if (PreCond) {
1653 // for (IV in 0..LastIteration) BODY;
1654 // <Final counter/linear vars updates>;
1655 // }
1656 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001657 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1658 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1659 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1660 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1661 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1662 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001663
Alexey Bataevf8365372017-11-17 17:57:25 +00001664 // Emit: if (PreCond) - begin.
1665 // If the condition constant folds and can be elided, avoid emitting the
1666 // whole loop.
1667 bool CondConstant;
1668 llvm::BasicBlock *ContBlock = nullptr;
1669 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1670 if (!CondConstant)
1671 return;
1672 } else {
1673 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1674 ContBlock = CGF.createBasicBlock("simd.if.end");
1675 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1676 CGF.getProfileCount(&S));
1677 CGF.EmitBlock(ThenBlock);
1678 CGF.incrementProfileCounter(&S);
1679 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001680
Alexey Bataevf8365372017-11-17 17:57:25 +00001681 // Emit the loop iteration variable.
1682 const Expr *IVExpr = S.getIterationVariable();
1683 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1684 CGF.EmitVarDecl(*IVDecl);
1685 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001686
Alexey Bataevf8365372017-11-17 17:57:25 +00001687 // Emit the iterations count variable.
1688 // If it is not a variable, Sema decided to calculate iterations count on
1689 // each iteration (e.g., it is foldable into a constant).
1690 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1691 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1692 // Emit calculation of the iterations count.
1693 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1694 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001695
Alexey Bataevf8365372017-11-17 17:57:25 +00001696 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001697
Alexey Bataevf8365372017-11-17 17:57:25 +00001698 emitAlignedClause(CGF, S);
1699 (void)CGF.EmitOMPLinearClauseInit(S);
1700 {
1701 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1702 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1703 CGF.EmitOMPLinearClause(S, LoopScope);
1704 CGF.EmitOMPPrivateClause(S, LoopScope);
1705 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1706 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1707 (void)LoopScope.Privatize();
1708 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1709 S.getInc(),
1710 [&S](CodeGenFunction &CGF) {
1711 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1712 CGF.EmitStopPoint(&S);
1713 },
1714 [](CodeGenFunction &) {});
1715 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001716 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001717 // Emit final copy of the lastprivate variables at the end of loops.
1718 if (HasLastprivateClause)
1719 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1720 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1721 emitPostUpdateForReductionClause(
1722 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1723 }
1724 CGF.EmitOMPLinearClauseFinal(
1725 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1726 // Emit: if (PreCond) - end.
1727 if (ContBlock) {
1728 CGF.EmitBranch(ContBlock);
1729 CGF.EmitBlock(ContBlock, true);
1730 }
1731}
1732
1733void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1734 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1735 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001736 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001737 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001738 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001739}
1740
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001741void CodeGenFunction::EmitOMPOuterLoop(
1742 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1743 CodeGenFunction::OMPPrivateScope &LoopScope,
1744 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1745 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1746 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001747 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001748
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001749 const Expr *IVExpr = S.getIterationVariable();
1750 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1751 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1752
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001753 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1754
1755 // Start the loop with a block that tests the condition.
1756 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1757 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001758 const SourceRange &R = S.getSourceRange();
1759 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1760 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001761
1762 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001763 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001764 // UB = min(UB, GlobalUB) or
1765 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1766 // 'distribute parallel for')
1767 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001768 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001769 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001770 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001771 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001772 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001773 BoolCondVal =
1774 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1775 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001777
1778 // If there are any cleanups between here and the loop-exit scope,
1779 // create a block to stage a loop exit along.
1780 auto ExitBlock = LoopExit.getBlock();
1781 if (LoopScope.requiresCleanups())
1782 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1783
1784 auto LoopBody = createBasicBlock("omp.dispatch.body");
1785 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1786 if (ExitBlock != LoopExit.getBlock()) {
1787 EmitBlock(ExitBlock);
1788 EmitBranchThroughCleanup(LoopExit);
1789 }
1790 EmitBlock(LoopBody);
1791
Alexander Musman92bdaab2015-03-12 13:37:50 +00001792 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1793 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001794 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001795 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001796
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001797 // Create a block for the increment.
1798 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1799 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1800
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001801 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1802 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001803 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1804 LoopStack.setParallel(!IsMonotonic);
1805 else
1806 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001807
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001808 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001809
1810 // when 'distribute' is not combined with a 'for':
1811 // while (idx <= UB) { BODY; ++idx; }
1812 // when 'distribute' is combined with a 'for'
1813 // (e.g. 'distribute parallel for')
1814 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1815 EmitOMPInnerLoop(
1816 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1817 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1818 CodeGenLoop(CGF, S, LoopExit);
1819 },
1820 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1821 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1822 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001823
1824 EmitBlock(Continue.getBlock());
1825 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001826 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001827 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001828 EmitIgnoredExpr(LoopArgs.NextLB);
1829 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001830 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001831
1832 EmitBranch(CondBlock);
1833 LoopStack.pop();
1834 // Emit the fall-through block.
1835 EmitBlock(LoopExit.getBlock());
1836
1837 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001838 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1839 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001840 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1841 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001842 };
1843 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001844}
1845
1846void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001847 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001848 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001849 const OMPLoopArguments &LoopArgs,
1850 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001851 auto &RT = CGM.getOpenMPRuntime();
1852
1853 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001854 const bool DynamicOrOrdered =
1855 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001856
1857 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001858 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001859 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001860 "static non-chunked schedule does not need outer loop");
1861
1862 // Emit outer loop.
1863 //
1864 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1865 // When schedule(dynamic,chunk_size) is specified, the iterations are
1866 // distributed to threads in the team in chunks as the threads request them.
1867 // Each thread executes a chunk of iterations, then requests another chunk,
1868 // until no chunks remain to be distributed. Each chunk contains chunk_size
1869 // iterations, except for the last chunk to be distributed, which may have
1870 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1871 //
1872 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1873 // to threads in the team in chunks as the executing threads request them.
1874 // Each thread executes a chunk of iterations, then requests another chunk,
1875 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1876 // each chunk is proportional to the number of unassigned iterations divided
1877 // by the number of threads in the team, decreasing to 1. For a chunk_size
1878 // with value k (greater than 1), the size of each chunk is determined in the
1879 // same way, with the restriction that the chunks do not contain fewer than k
1880 // iterations (except for the last chunk to be assigned, which may have fewer
1881 // than k iterations).
1882 //
1883 // When schedule(auto) is specified, the decision regarding scheduling is
1884 // delegated to the compiler and/or runtime system. The programmer gives the
1885 // implementation the freedom to choose any possible mapping of iterations to
1886 // threads in the team.
1887 //
1888 // When schedule(runtime) is specified, the decision regarding scheduling is
1889 // deferred until run time, and the schedule and chunk size are taken from the
1890 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1891 // implementation defined
1892 //
1893 // while(__kmpc_dispatch_next(&LB, &UB)) {
1894 // idx = LB;
1895 // while (idx <= UB) { BODY; ++idx;
1896 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1897 // } // inner loop
1898 // }
1899 //
1900 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1901 // When schedule(static, chunk_size) is specified, iterations are divided into
1902 // chunks of size chunk_size, and the chunks are assigned to the threads in
1903 // the team in a round-robin fashion in the order of the thread number.
1904 //
1905 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1906 // while (idx <= UB) { BODY; ++idx; } // inner loop
1907 // LB = LB + ST;
1908 // UB = UB + ST;
1909 // }
1910 //
1911
1912 const Expr *IVExpr = S.getIterationVariable();
1913 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1914 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1915
1916 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001917 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1918 llvm::Value *LBVal = DispatchBounds.first;
1919 llvm::Value *UBVal = DispatchBounds.second;
1920 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1921 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001922 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001923 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001924 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001925 CGOpenMPRuntime::StaticRTInput StaticInit(
1926 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1927 LoopArgs.ST, LoopArgs.Chunk);
1928 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1929 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001930 }
1931
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001932 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1933 const unsigned IVSize,
1934 const bool IVSigned) {
1935 if (Ordered) {
1936 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1937 IVSigned);
1938 }
1939 };
1940
1941 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1942 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1943 OuterLoopArgs.IncExpr = S.getInc();
1944 OuterLoopArgs.Init = S.getInit();
1945 OuterLoopArgs.Cond = S.getCond();
1946 OuterLoopArgs.NextLB = S.getNextLowerBound();
1947 OuterLoopArgs.NextUB = S.getNextUpperBound();
1948 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1949 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001950}
1951
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001952static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1953 const unsigned IVSize, const bool IVSigned) {}
1954
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001955void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001956 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1957 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1958 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001959
1960 auto &RT = CGM.getOpenMPRuntime();
1961
1962 // Emit outer loop.
1963 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1964 // dynamic
1965 //
1966
1967 const Expr *IVExpr = S.getIterationVariable();
1968 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1969 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1970
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001971 CGOpenMPRuntime::StaticRTInput StaticInit(
1972 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1973 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1974 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001975
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001976 // for combined 'distribute' and 'for' the increment expression of distribute
1977 // is store in DistInc. For 'distribute' alone, it is in Inc.
1978 Expr *IncExpr;
1979 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1980 IncExpr = S.getDistInc();
1981 else
1982 IncExpr = S.getInc();
1983
1984 // this routine is shared by 'omp distribute parallel for' and
1985 // 'omp distribute': select the right EUB expression depending on the
1986 // directive
1987 OMPLoopArguments OuterLoopArgs;
1988 OuterLoopArgs.LB = LoopArgs.LB;
1989 OuterLoopArgs.UB = LoopArgs.UB;
1990 OuterLoopArgs.ST = LoopArgs.ST;
1991 OuterLoopArgs.IL = LoopArgs.IL;
1992 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1993 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1994 ? S.getCombinedEnsureUpperBound()
1995 : S.getEnsureUpperBound();
1996 OuterLoopArgs.IncExpr = IncExpr;
1997 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1998 ? S.getCombinedInit()
1999 : S.getInit();
2000 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2001 ? S.getCombinedCond()
2002 : S.getCond();
2003 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2004 ? S.getCombinedNextLowerBound()
2005 : S.getNextLowerBound();
2006 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2007 ? S.getCombinedNextUpperBound()
2008 : S.getNextUpperBound();
2009
2010 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2011 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2012 emitEmptyOrdered);
2013}
2014
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002015static std::pair<LValue, LValue>
2016emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2017 const OMPExecutableDirective &S) {
2018 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2019 LValue LB =
2020 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2021 LValue UB =
2022 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2023
2024 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2025 // parallel for') we need to use the 'distribute'
2026 // chunk lower and upper bounds rather than the whole loop iteration
2027 // space. These are parameters to the outlined function for 'parallel'
2028 // and we copy the bounds of the previous schedule into the
2029 // the current ones.
2030 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2031 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2032 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
2033 PrevLBVal = CGF.EmitScalarConversion(
2034 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2035 LS.getIterationVariable()->getType(), SourceLocation());
2036 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
2037 PrevUBVal = CGF.EmitScalarConversion(
2038 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2039 LS.getIterationVariable()->getType(), SourceLocation());
2040
2041 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2042 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2043
2044 return {LB, UB};
2045}
2046
2047/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2048/// we need to use the LB and UB expressions generated by the worksharing
2049/// code generation support, whereas in non combined situations we would
2050/// just emit 0 and the LastIteration expression
2051/// This function is necessary due to the difference of the LB and UB
2052/// types for the RT emission routines for 'for_static_init' and
2053/// 'for_dispatch_init'
2054static std::pair<llvm::Value *, llvm::Value *>
2055emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2056 const OMPExecutableDirective &S,
2057 Address LB, Address UB) {
2058 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2059 const Expr *IVExpr = LS.getIterationVariable();
2060 // when implementing a dynamic schedule for a 'for' combined with a
2061 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2062 // is not normalized as each team only executes its own assigned
2063 // distribute chunk
2064 QualType IteratorTy = IVExpr->getType();
2065 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
2066 SourceLocation());
2067 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
2068 SourceLocation());
2069 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002070}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002071
2072static void emitDistributeParallelForDistributeInnerBoundParams(
2073 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2074 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2075 const auto &Dir = cast<OMPLoopDirective>(S);
2076 LValue LB =
2077 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2078 auto LBCast = CGF.Builder.CreateIntCast(
2079 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2080 CapturedVars.push_back(LBCast);
2081 LValue UB =
2082 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2083
2084 auto UBCast = CGF.Builder.CreateIntCast(
2085 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2086 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002087}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002088
2089static void
2090emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2091 const OMPLoopDirective &S,
2092 CodeGenFunction::JumpDest LoopExit) {
2093 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2094 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002095 bool HasCancel = false;
2096 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2097 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2098 HasCancel = D->hasCancel();
2099 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2100 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002101 else if (const auto *D =
2102 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2103 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002104 }
2105 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2106 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002107 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2108 emitDistributeParallelForInnerBounds,
2109 emitDistributeParallelForDispatchBounds);
2110 };
2111
2112 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002113 CGF, S,
2114 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2115 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002117}
2118
Carlo Bertolli9925f152016-06-27 14:55:37 +00002119void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2120 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002121 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2122 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2123 S.getDistInc());
2124 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002125 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00002126 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002127}
2128
Kelvin Li4a39add2016-07-05 05:00:15 +00002129void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2130 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002131 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2132 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2133 S.getDistInc());
2134 };
Kelvin Li4a39add2016-07-05 05:00:15 +00002135 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002136 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002137}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002138
2139void CodeGenFunction::EmitOMPDistributeSimdDirective(
2140 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002141 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2142 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2143 };
Kelvin Li787f3fc2016-07-06 04:45:38 +00002144 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002145 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002146}
2147
Alexey Bataevf8365372017-11-17 17:57:25 +00002148void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2149 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2150 // Emit SPMD target parallel for region as a standalone region.
2151 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2152 emitOMPSimdRegion(CGF, S, Action);
2153 };
2154 llvm::Function *Fn;
2155 llvm::Constant *Addr;
2156 // Emit target region as a standalone region.
2157 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2158 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2159 assert(Fn && Addr && "Target device function emission failed.");
2160}
2161
Kelvin Li986330c2016-07-20 22:57:10 +00002162void CodeGenFunction::EmitOMPTargetSimdDirective(
2163 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002164 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2165 emitOMPSimdRegion(CGF, S, Action);
2166 };
2167 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002168}
2169
Kelvin Li1851df52017-01-03 05:23:48 +00002170void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2171 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002172 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002173 CGM.getOpenMPRuntime().emitInlinedDirective(
2174 *this, OMPD_target_teams_distribute_parallel_for_simd,
2175 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2176 CGF.EmitStmt(
2177 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2178 });
2179}
2180
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002181namespace {
2182 struct ScheduleKindModifiersTy {
2183 OpenMPScheduleClauseKind Kind;
2184 OpenMPScheduleClauseModifier M1;
2185 OpenMPScheduleClauseModifier M2;
2186 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2187 OpenMPScheduleClauseModifier M1,
2188 OpenMPScheduleClauseModifier M2)
2189 : Kind(Kind), M1(M1), M2(M2) {}
2190 };
2191} // namespace
2192
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002193bool CodeGenFunction::EmitOMPWorksharingLoop(
2194 const OMPLoopDirective &S, Expr *EUB,
2195 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2196 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002197 // Emit the loop iteration variable.
2198 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2199 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2200 EmitVarDecl(*IVDecl);
2201
2202 // Emit the iterations count variable.
2203 // If it is not a variable, Sema decided to calculate iterations count on each
2204 // iteration (e.g., it is foldable into a constant).
2205 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2206 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2207 // Emit calculation of the iterations count.
2208 EmitIgnoredExpr(S.getCalcLastIteration());
2209 }
2210
2211 auto &RT = CGM.getOpenMPRuntime();
2212
Alexey Bataev38e89532015-04-16 04:54:05 +00002213 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002214 // Check pre-condition.
2215 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002216 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002217 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002218 // If the condition constant folds and can be elided, avoid emitting the
2219 // whole loop.
2220 bool CondConstant;
2221 llvm::BasicBlock *ContBlock = nullptr;
2222 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2223 if (!CondConstant)
2224 return false;
2225 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002226 auto *ThenBlock = createBasicBlock("omp.precond.then");
2227 ContBlock = createBasicBlock("omp.precond.end");
2228 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002229 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002230 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002231 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002232 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002233
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 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002370 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002371 if (ContBlock) {
2372 EmitBranch(ContBlock);
2373 EmitBlock(ContBlock, true);
2374 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002375 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002376 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002377}
2378
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002379/// The following two functions generate expressions for the loop lower
2380/// and upper bounds in case of static and dynamic (dispatch) schedule
2381/// of the associated 'for' or 'distribute' loop.
2382static std::pair<LValue, LValue>
2383emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2384 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2385 LValue LB =
2386 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2387 LValue UB =
2388 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2389 return {LB, UB};
2390}
2391
2392/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2393/// consider the lower and upper bound expressions generated by the
2394/// worksharing loop support, but we use 0 and the iteration space size as
2395/// constants
2396static std::pair<llvm::Value *, llvm::Value *>
2397emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2398 Address LB, Address UB) {
2399 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2400 const Expr *IVExpr = LS.getIterationVariable();
2401 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2402 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2403 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2404 return {LBVal, UBVal};
2405}
2406
Alexander Musmanc6388682014-12-15 07:07:06 +00002407void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002408 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002409 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2410 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002411 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002412 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2413 emitForLoopBounds,
2414 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002416 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002417 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002418 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2419 S.hasCancel());
2420 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002421
2422 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002423 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002424 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2425 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002426}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002427
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002428void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002429 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2431 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002432 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2433 emitForLoopBounds,
2434 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002435 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002436 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002437 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002438 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2439 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002440
2441 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002442 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002443 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2444 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002445}
2446
Alexey Bataev2df54a02015-03-12 08:53:29 +00002447static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2448 const Twine &Name,
2449 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002450 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002451 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002452 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002453 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002454}
2455
Alexey Bataev3392d762016-02-16 11:18:12 +00002456void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002457 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2458 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002459 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2461 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002462 auto &C = CGF.CGM.getContext();
2463 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2464 // Emit helper vars inits.
2465 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2466 CGF.Builder.getInt32(0));
2467 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2468 : CGF.Builder.getInt32(0);
2469 LValue UB =
2470 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2471 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2472 CGF.Builder.getInt32(1));
2473 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2474 CGF.Builder.getInt32(0));
2475 // Loop counter.
2476 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2477 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2478 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2479 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2480 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2481 // Generate condition for loop.
2482 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002483 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002484 // Increment for loop counter.
2485 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2486 S.getLocStart());
2487 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2488 // Iterate through all sections and emit a switch construct:
2489 // switch (IV) {
2490 // case 0:
2491 // <SectionStmt[0]>;
2492 // break;
2493 // ...
2494 // case <NumSection> - 1:
2495 // <SectionStmt[<NumSection> - 1]>;
2496 // break;
2497 // }
2498 // .omp.sections.exit:
2499 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2500 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2501 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2502 CS == nullptr ? 1 : CS->size());
2503 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002504 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002505 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002506 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2507 CGF.EmitBlock(CaseBB);
2508 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002509 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002510 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002511 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002512 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002513 } else {
2514 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2515 CGF.EmitBlock(CaseBB);
2516 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2517 CGF.EmitStmt(Stmt);
2518 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002519 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002520 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002521 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002522
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002523 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2524 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002525 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002526 // initialization of firstprivate variables and post-update of lastprivate
2527 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002528 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2529 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2530 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002531 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002532 CGF.EmitOMPPrivateClause(S, LoopScope);
2533 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2534 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2535 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002536
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002537 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002538 OpenMPScheduleTy ScheduleKind;
2539 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002540 CGOpenMPRuntime::StaticRTInput StaticInit(
2541 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2542 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002543 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002544 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002545 // UB = min(UB, GlobalUB);
2546 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2547 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2548 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2549 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2550 // IV = LB;
2551 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2552 // while (idx <= UB) { BODY; ++idx; }
2553 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2554 [](CodeGenFunction &) {});
2555 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002556 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002557 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2558 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002559 };
2560 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002561 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002562 // Emit post-update of the reduction variables if IsLastIter != 0.
2563 emitPostUpdateForReductionClause(
2564 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2565 return CGF.Builder.CreateIsNotNull(
2566 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2567 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002568
2569 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2570 if (HasLastprivates)
2571 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002572 S, /*NoFinals=*/false,
2573 CGF.Builder.CreateIsNotNull(
2574 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002575 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002576
2577 bool HasCancel = false;
2578 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2579 HasCancel = OSD->hasCancel();
2580 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2581 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002582 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002583 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2584 HasCancel);
2585 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2586 // clause. Otherwise the barrier will be generated by the codegen for the
2587 // directive.
2588 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002589 // Emit implicit barrier to synchronize threads and avoid data races on
2590 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002591 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2592 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002593 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002594}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002595
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002596void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002597 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002598 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002599 EmitSections(S);
2600 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002601 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002602 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002603 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2604 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002605 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002606}
2607
2608void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002609 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002611 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002612 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002613 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2614 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002615}
2616
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002617void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002618 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002619 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002620 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002621 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002622 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002623 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002624 // Build a list of copyprivate variables along with helper expressions
2625 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002626 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002627 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002628 DestExprs.append(C->destination_exprs().begin(),
2629 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002630 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002631 AssignmentOps.append(C->assignment_ops().begin(),
2632 C->assignment_ops().end());
2633 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002634 // Emit code for 'single' region along with 'copyprivate' clauses
2635 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2636 Action.Enter(CGF);
2637 OMPPrivateScope SingleScope(CGF);
2638 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2639 CGF.EmitOMPPrivateClause(S, SingleScope);
2640 (void)SingleScope.Privatize();
2641 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2642 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002643 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002644 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002645 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2646 CopyprivateVars, DestExprs,
2647 SrcExprs, AssignmentOps);
2648 }
2649 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2650 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002651 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002652 CGM.getOpenMPRuntime().emitBarrierCall(
2653 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002654 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002655 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002656}
2657
Alexey Bataev8d690652014-12-04 07:23:53 +00002658void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002659 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2660 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002662 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002663 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002665}
2666
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002667void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002668 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2669 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002670 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002671 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002672 Expr *Hint = nullptr;
2673 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2674 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002675 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002676 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2677 S.getDirectiveName().getAsString(),
2678 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002679}
2680
Alexey Bataev671605e2015-04-13 05:28:11 +00002681void CodeGenFunction::EmitOMPParallelForDirective(
2682 const OMPParallelForDirective &S) {
2683 // Emit directive as a combined directive that consists of two implicit
2684 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002685 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002686 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002687 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2688 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002689 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002690 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2691 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002692}
2693
Alexander Musmane4e893b2014-09-23 09:33:00 +00002694void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002695 const OMPParallelForSimdDirective &S) {
2696 // Emit directive as a combined directive that consists of two implicit
2697 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002698 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002699 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2700 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002701 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002702 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2703 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002704}
2705
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002706void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002707 const OMPParallelSectionsDirective &S) {
2708 // Emit directive as a combined directive that consists of two implicit
2709 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002710 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2711 CGF.EmitSections(S);
2712 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002713 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2714 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002715}
2716
Alexey Bataev7292c292016-04-25 12:22:29 +00002717void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2718 const RegionCodeGenTy &BodyGen,
2719 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002720 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002721 // Emit outlined function for task construct.
2722 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002723 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002724 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002725 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002726 // Check if the task is final
2727 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2728 // If the condition constant folds and can be elided, try to avoid emitting
2729 // the condition and the dead arm of the if/else.
2730 auto *Cond = Clause->getCondition();
2731 bool CondConstant;
2732 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2733 Data.Final.setInt(CondConstant);
2734 else
2735 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2736 } else {
2737 // By default the task is not final.
2738 Data.Final.setInt(/*IntVal=*/false);
2739 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002740 // Check if the task has 'priority' clause.
2741 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002742 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002743 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002744 Data.Priority.setPointer(EmitScalarConversion(
2745 EmitScalarExpr(Prio), Prio->getType(),
2746 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2747 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002748 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002749 // The first function argument for tasks is a thread id, the second one is a
2750 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002751 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2752 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002753 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002754 auto IRef = C->varlist_begin();
2755 for (auto *IInit : C->private_copies()) {
2756 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2757 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002758 Data.PrivateVars.push_back(*IRef);
2759 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002760 }
2761 ++IRef;
2762 }
2763 }
2764 EmittedAsPrivate.clear();
2765 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002766 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002767 auto IRef = C->varlist_begin();
2768 auto IElemInitRef = C->inits().begin();
2769 for (auto *IInit : C->private_copies()) {
2770 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2771 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002772 Data.FirstprivateVars.push_back(*IRef);
2773 Data.FirstprivateCopies.push_back(IInit);
2774 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002775 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002776 ++IRef;
2777 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002778 }
2779 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002780 // Get list of lastprivate variables (for taskloops).
2781 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2782 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2783 auto IRef = C->varlist_begin();
2784 auto ID = C->destination_exprs().begin();
2785 for (auto *IInit : C->private_copies()) {
2786 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2787 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2788 Data.LastprivateVars.push_back(*IRef);
2789 Data.LastprivateCopies.push_back(IInit);
2790 }
2791 LastprivateDstsOrigs.insert(
2792 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2793 cast<DeclRefExpr>(*IRef)});
2794 ++IRef;
2795 ++ID;
2796 }
2797 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002798 SmallVector<const Expr *, 4> LHSs;
2799 SmallVector<const Expr *, 4> RHSs;
2800 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2801 auto IPriv = C->privates().begin();
2802 auto IRed = C->reduction_ops().begin();
2803 auto ILHS = C->lhs_exprs().begin();
2804 auto IRHS = C->rhs_exprs().begin();
2805 for (const auto *Ref : C->varlists()) {
2806 Data.ReductionVars.emplace_back(Ref);
2807 Data.ReductionCopies.emplace_back(*IPriv);
2808 Data.ReductionOps.emplace_back(*IRed);
2809 LHSs.emplace_back(*ILHS);
2810 RHSs.emplace_back(*IRHS);
2811 std::advance(IPriv, 1);
2812 std::advance(IRed, 1);
2813 std::advance(ILHS, 1);
2814 std::advance(IRHS, 1);
2815 }
2816 }
2817 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2818 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002819 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002820 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2821 for (auto *IRef : C->varlists())
2822 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002823 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002824 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002825 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002826 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002827 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2828 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002829 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002830 auto *CopyFn = CGF.Builder.CreateLoad(
2831 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2832 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2833 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2834 // Map privates.
2835 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2836 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2837 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002838 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002839 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2840 Address PrivatePtr = CGF.CreateMemTemp(
2841 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2842 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2843 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002844 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002845 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002846 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2847 Address PrivatePtr =
2848 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2849 ".firstpriv.ptr.addr");
2850 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2851 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002852 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002853 for (auto *E : Data.LastprivateVars) {
2854 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2855 Address PrivatePtr =
2856 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2857 ".lastpriv.ptr.addr");
2858 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2859 CallArgs.push_back(PrivatePtr.getPointer());
2860 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002861 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2862 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002863 for (auto &&Pair : LastprivateDstsOrigs) {
2864 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2865 DeclRefExpr DRE(
2866 const_cast<VarDecl *>(OrigVD),
2867 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2868 OrigVD) != nullptr,
2869 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2870 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2871 return CGF.EmitLValue(&DRE).getAddress();
2872 });
2873 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002874 for (auto &&Pair : PrivatePtrs) {
2875 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2876 CGF.getContext().getDeclAlign(Pair.first));
2877 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2878 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002879 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002880 if (Data.Reductions) {
2881 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2882 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2883 Data.ReductionOps);
2884 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2885 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2886 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2887 RedCG.emitSharedLValue(CGF, Cnt);
2888 RedCG.emitAggregateType(CGF, Cnt);
2889 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2890 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2891 Replacement =
2892 Address(CGF.EmitScalarConversion(
2893 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2894 CGF.getContext().getPointerType(
2895 Data.ReductionCopies[Cnt]->getType()),
2896 SourceLocation()),
2897 Replacement.getAlignment());
2898 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2899 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2900 [Replacement]() { return Replacement; });
2901 // FIXME: This must removed once the runtime library is fixed.
2902 // Emit required threadprivate variables for
2903 // initilizer/combiner/finalizer.
2904 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2905 RedCG, Cnt);
2906 }
2907 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002908 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002910 SmallVector<const Expr *, 4> InRedVars;
2911 SmallVector<const Expr *, 4> InRedPrivs;
2912 SmallVector<const Expr *, 4> InRedOps;
2913 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2914 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2915 auto IPriv = C->privates().begin();
2916 auto IRed = C->reduction_ops().begin();
2917 auto ITD = C->taskgroup_descriptors().begin();
2918 for (const auto *Ref : C->varlists()) {
2919 InRedVars.emplace_back(Ref);
2920 InRedPrivs.emplace_back(*IPriv);
2921 InRedOps.emplace_back(*IRed);
2922 TaskgroupDescriptors.emplace_back(*ITD);
2923 std::advance(IPriv, 1);
2924 std::advance(IRed, 1);
2925 std::advance(ITD, 1);
2926 }
2927 }
2928 // Privatize in_reduction items here, because taskgroup descriptors must be
2929 // privatized earlier.
2930 OMPPrivateScope InRedScope(CGF);
2931 if (!InRedVars.empty()) {
2932 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2933 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2934 RedCG.emitSharedLValue(CGF, Cnt);
2935 RedCG.emitAggregateType(CGF, Cnt);
2936 // The taskgroup descriptor variable is always implicit firstprivate and
2937 // privatized already during procoessing of the firstprivates.
2938 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2939 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2940 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2941 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2942 Replacement = Address(
2943 CGF.EmitScalarConversion(
2944 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2945 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2946 SourceLocation()),
2947 Replacement.getAlignment());
2948 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2949 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2950 [Replacement]() { return Replacement; });
2951 // FIXME: This must removed once the runtime library is fixed.
2952 // Emit required threadprivate variables for
2953 // initilizer/combiner/finalizer.
2954 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2955 RedCG, Cnt);
2956 }
2957 }
2958 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002959
2960 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002961 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002962 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002963 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2964 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2965 Data.NumberOfParts);
2966 OMPLexicalScope Scope(*this, S);
2967 TaskGen(*this, OutlinedFn, Data);
2968}
2969
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002970static ImplicitParamDecl *
2971createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
2972 QualType Ty, CapturedDecl *CD) {
2973 auto *OrigVD = ImplicitParamDecl::Create(
2974 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2975 auto *OrigRef =
2976 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2977 /*RefersToEnclosingVariableOrCapture=*/false,
2978 SourceLocation(), Ty, VK_LValue);
2979 auto *PrivateVD = ImplicitParamDecl::Create(
2980 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2981 auto *PrivateRef = DeclRefExpr::Create(
2982 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
2983 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(), Ty,
2984 VK_LValue);
2985 QualType ElemType = C.getBaseElementType(Ty);
2986 auto *InitVD =
2987 ImplicitParamDecl::Create(C, CD, SourceLocation(), /*Id=*/nullptr,
2988 ElemType, ImplicitParamDecl::Other);
2989 auto *InitRef =
2990 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2991 /*RefersToEnclosingVariableOrCapture=*/false,
2992 SourceLocation(), ElemType, VK_LValue);
2993 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);
3039 BPVD = createImplicitFirstprivateForType(getContext(), Data,
3040 BaseAndPointersType, CD);
3041 PVD = createImplicitFirstprivateForType(getContext(), Data,
3042 BaseAndPointersType, CD);
3043 QualType SizesType = getContext().getConstantArrayType(
3044 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3045 /*IndexTypeQuals=*/0);
3046 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD);
3047 TargetScope.addPrivate(
3048 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3049 TargetScope.addPrivate(PVD,
3050 [&InputInfo]() { return InputInfo.PointersArray; });
3051 TargetScope.addPrivate(SVD,
3052 [&InputInfo]() { return InputInfo.SizesArray; });
3053 }
3054 (void)TargetScope.Privatize();
3055 // Build list of dependences.
3056 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3057 for (auto *IRef : C->varlists())
3058 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3059 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3060 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3061 // Set proper addresses for generated private copies.
3062 OMPPrivateScope Scope(CGF);
3063 if (!Data.FirstprivateVars.empty()) {
3064 enum { PrivatesParam = 2, CopyFnParam = 3 };
3065 auto *CopyFn = CGF.Builder.CreateLoad(
3066 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3067 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3068 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3069 // Map privates.
3070 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3071 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3072 CallArgs.push_back(PrivatesPtr);
3073 for (auto *E : Data.FirstprivateVars) {
3074 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3075 Address PrivatePtr =
3076 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3077 ".firstpriv.ptr.addr");
3078 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3079 CallArgs.push_back(PrivatePtr.getPointer());
3080 }
3081 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3082 CopyFn, CallArgs);
3083 for (auto &&Pair : PrivatePtrs) {
3084 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3085 CGF.getContext().getDeclAlign(Pair.first));
3086 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3087 }
3088 }
3089 // Privatize all private variables except for in_reduction items.
3090 (void)Scope.Privatize();
3091 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3092 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3093 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3094 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3095 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3096 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3097
3098 Action.Enter(CGF);
3099 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true,
3100 /*EmitPreInitStmt=*/false);
3101 BodyGen(CGF);
3102 };
3103 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3104 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3105 Data.NumberOfParts);
3106 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3107 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3108 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3109 SourceLocation());
3110
3111 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3112 SharedsTy, CapturedStruct, &IfCond, Data);
3113}
3114
Alexey Bataev7292c292016-04-25 12:22:29 +00003115void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3116 // Emit outlined function for task construct.
3117 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3118 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003119 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003120 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003121 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3122 if (C->getNameModifier() == OMPD_unknown ||
3123 C->getNameModifier() == OMPD_task) {
3124 IfCond = C->getCondition();
3125 break;
3126 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003127 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003128
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003129 OMPTaskDataTy Data;
3130 // Check if we should emit tied or untied task.
3131 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003132 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3133 CGF.EmitStmt(CS->getCapturedStmt());
3134 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003135 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003136 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003137 const OMPTaskDataTy &Data) {
3138 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3139 SharedsTy, CapturedStruct, IfCond,
3140 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003141 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003142 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003143}
3144
Alexey Bataev9f797f32015-02-05 05:57:51 +00003145void CodeGenFunction::EmitOMPTaskyieldDirective(
3146 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003147 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003148}
3149
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003150void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003151 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003152}
3153
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003154void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3155 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003156}
3157
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003158void CodeGenFunction::EmitOMPTaskgroupDirective(
3159 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3161 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003162 if (const Expr *E = S.getReductionRef()) {
3163 SmallVector<const Expr *, 4> LHSs;
3164 SmallVector<const Expr *, 4> RHSs;
3165 OMPTaskDataTy Data;
3166 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3167 auto IPriv = C->privates().begin();
3168 auto IRed = C->reduction_ops().begin();
3169 auto ILHS = C->lhs_exprs().begin();
3170 auto IRHS = C->rhs_exprs().begin();
3171 for (const auto *Ref : C->varlists()) {
3172 Data.ReductionVars.emplace_back(Ref);
3173 Data.ReductionCopies.emplace_back(*IPriv);
3174 Data.ReductionOps.emplace_back(*IRed);
3175 LHSs.emplace_back(*ILHS);
3176 RHSs.emplace_back(*IRHS);
3177 std::advance(IPriv, 1);
3178 std::advance(IRed, 1);
3179 std::advance(ILHS, 1);
3180 std::advance(IRHS, 1);
3181 }
3182 }
3183 llvm::Value *ReductionDesc =
3184 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3185 LHSs, RHSs, Data);
3186 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3187 CGF.EmitVarDecl(*VD);
3188 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3189 /*Volatile=*/false, E->getType());
3190 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003191 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003192 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003193 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003194 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3195}
3196
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003197void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003198 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003199 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003200 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3201 FlushClause->varlist_end());
3202 }
3203 return llvm::None;
3204 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003205}
3206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003207void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3208 const CodeGenLoopTy &CodeGenLoop,
3209 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003210 // Emit the loop iteration variable.
3211 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3212 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3213 EmitVarDecl(*IVDecl);
3214
3215 // Emit the iterations count variable.
3216 // If it is not a variable, Sema decided to calculate iterations count on each
3217 // iteration (e.g., it is foldable into a constant).
3218 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3219 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3220 // Emit calculation of the iterations count.
3221 EmitIgnoredExpr(S.getCalcLastIteration());
3222 }
3223
3224 auto &RT = CGM.getOpenMPRuntime();
3225
Carlo Bertolli962bb802017-01-03 18:24:42 +00003226 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003227 // Check pre-condition.
3228 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003229 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003230 // Skip the entire loop if we don't meet the precondition.
3231 // If the condition constant folds and can be elided, avoid emitting the
3232 // whole loop.
3233 bool CondConstant;
3234 llvm::BasicBlock *ContBlock = nullptr;
3235 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3236 if (!CondConstant)
3237 return;
3238 } else {
3239 auto *ThenBlock = createBasicBlock("omp.precond.then");
3240 ContBlock = createBasicBlock("omp.precond.end");
3241 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3242 getProfileCount(&S));
3243 EmitBlock(ThenBlock);
3244 incrementProfileCounter(&S);
3245 }
3246
Alexey Bataev617db5f2017-12-04 15:38:33 +00003247 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003248 // Emit 'then' code.
3249 {
3250 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003251
3252 LValue LB = EmitOMPHelperVar(
3253 *this, cast<DeclRefExpr>(
3254 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3255 ? S.getCombinedLowerBoundVariable()
3256 : S.getLowerBoundVariable())));
3257 LValue UB = EmitOMPHelperVar(
3258 *this, cast<DeclRefExpr>(
3259 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3260 ? S.getCombinedUpperBoundVariable()
3261 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003262 LValue ST =
3263 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3264 LValue IL =
3265 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3266
3267 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003268 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003269 // Emit implicit barrier to synchronize threads and avoid data races
3270 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003271 // lastprivate variables.
3272 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003273 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3274 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003275 }
3276 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003277 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003278 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3279 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003280 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003281 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003282 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003283 (void)LoopScope.Privatize();
3284
3285 // Detect the distribute schedule kind and chunk.
3286 llvm::Value *Chunk = nullptr;
3287 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3288 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3289 ScheduleKind = C->getDistScheduleKind();
3290 if (const auto *Ch = C->getChunkSize()) {
3291 Chunk = EmitScalarExpr(Ch);
3292 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003293 S.getIterationVariable()->getType(),
3294 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003295 }
3296 }
3297 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3298 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3299
3300 // OpenMP [2.10.8, distribute Construct, Description]
3301 // If dist_schedule is specified, kind must be static. If specified,
3302 // iterations are divided into chunks of size chunk_size, chunks are
3303 // assigned to the teams of the league in a round-robin fashion in the
3304 // order of the team number. When no chunk_size is specified, the
3305 // iteration space is divided into chunks that are approximately equal
3306 // in size, and at most one chunk is distributed to each team of the
3307 // league. The size of the chunks is unspecified in this case.
3308 if (RT.isStaticNonchunked(ScheduleKind,
3309 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003310 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3311 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003312 CGOpenMPRuntime::StaticRTInput StaticInit(
3313 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3314 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003315 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003316 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317 auto LoopExit =
3318 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3319 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003320 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3321 ? S.getCombinedEnsureUpperBound()
3322 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003323 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003324 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3325 ? S.getCombinedInit()
3326 : S.getInit());
3327
3328 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3329 ? S.getCombinedCond()
3330 : S.getCond();
3331
3332 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003333 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003334 // when combined with 'for' (e.g. as in 'distribute parallel for')
3335 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3336 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3337 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3338 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003339 },
3340 [](CodeGenFunction &) {});
3341 EmitBlock(LoopExit.getBlock());
3342 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003343 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003344 } else {
3345 // Emit the outer loop, which requests its work chunk [LB..UB] from
3346 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003347 const OMPLoopArguments LoopArguments = {
3348 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3349 Chunk};
3350 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3351 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003352 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003353 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3354 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3355 return CGF.Builder.CreateIsNotNull(
3356 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3357 });
3358 }
3359 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3360 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3361 isOpenMPSimdDirective(S.getDirectiveKind())) {
3362 ReductionKind = OMPD_parallel_for_simd;
3363 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3364 ReductionKind = OMPD_parallel_for;
3365 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3366 ReductionKind = OMPD_simd;
3367 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3368 S.hasClausesOfKind<OMPReductionClause>()) {
3369 llvm_unreachable(
3370 "No reduction clauses is allowed in distribute directive.");
3371 }
3372 EmitOMPReductionClauseFinal(S, ReductionKind);
3373 // Emit post-update of the reduction variables if IsLastIter != 0.
3374 emitPostUpdateForReductionClause(
3375 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3376 return CGF.Builder.CreateIsNotNull(
3377 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3378 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003379 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003380 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003381 EmitOMPLastprivateClauseFinal(
3382 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003383 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3384 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385 }
3386
3387 // We're now done with the loop, so jump to the continuation block.
3388 if (ContBlock) {
3389 EmitBranch(ContBlock);
3390 EmitBlock(ContBlock, true);
3391 }
3392 }
3393}
3394
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003395void CodeGenFunction::EmitOMPDistributeDirective(
3396 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003397 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003398
3399 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003400 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003401 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003402 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003403}
3404
Alexey Bataev5f600d62015-09-29 03:48:57 +00003405static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3406 const CapturedStmt *S) {
3407 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3408 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3409 CGF.CapturedStmtInfo = &CapStmtInfo;
3410 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3411 Fn->addFnAttr(llvm::Attribute::NoInline);
3412 return Fn;
3413}
3414
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003415void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003416 if (!S.getAssociatedStmt()) {
3417 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3418 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003419 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003420 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003421 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003422 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3423 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003424 if (C) {
3425 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3426 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3427 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3428 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003429 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3430 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003431 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003432 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003433 CGF.EmitStmt(
3434 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3435 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003436 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003437 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003438 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003439}
3440
Alexey Bataevb57056f2015-01-22 06:17:56 +00003441static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003442 QualType SrcType, QualType DestType,
3443 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003444 assert(CGF.hasScalarEvaluationKind(DestType) &&
3445 "DestType must have scalar evaluation kind.");
3446 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3447 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003448 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3449 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003450 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003451 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003452}
3453
3454static CodeGenFunction::ComplexPairTy
3455convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003456 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003457 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3458 "DestType must have complex evaluation kind.");
3459 CodeGenFunction::ComplexPairTy ComplexVal;
3460 if (Val.isScalar()) {
3461 // Convert the input element to the element type of the complex.
3462 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003463 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3464 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003465 ComplexVal = CodeGenFunction::ComplexPairTy(
3466 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3467 } else {
3468 assert(Val.isComplex() && "Must be a scalar or complex.");
3469 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3470 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3471 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003472 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003473 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003474 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003475 }
3476 return ComplexVal;
3477}
3478
Alexey Bataev5e018f92015-04-23 06:35:10 +00003479static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3480 LValue LVal, RValue RVal) {
3481 if (LVal.isGlobalReg()) {
3482 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3483 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003484 CGF.EmitAtomicStore(RVal, LVal,
3485 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3486 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003487 LVal.isVolatile(), /*IsInit=*/false);
3488 }
3489}
3490
Alexey Bataev8524d152016-01-21 12:35:58 +00003491void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3492 QualType RValTy, SourceLocation Loc) {
3493 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003494 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003495 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3496 *this, RVal, RValTy, LVal.getType(), Loc)),
3497 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003498 break;
3499 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003500 EmitStoreOfComplex(
3501 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003502 /*isInit=*/false);
3503 break;
3504 case TEK_Aggregate:
3505 llvm_unreachable("Must be a scalar or complex.");
3506 }
3507}
3508
Alexey Bataevb57056f2015-01-22 06:17:56 +00003509static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3510 const Expr *X, const Expr *V,
3511 SourceLocation Loc) {
3512 // v = x;
3513 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3514 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3515 LValue XLValue = CGF.EmitLValue(X);
3516 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003517 RValue Res = XLValue.isGlobalReg()
3518 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003519 : CGF.EmitAtomicLoad(
3520 XLValue, Loc,
3521 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3522 : llvm::AtomicOrdering::Monotonic,
3523 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003524 // OpenMP, 2.12.6, atomic Construct
3525 // Any atomic construct with a seq_cst clause forces the atomically
3526 // performed operation to include an implicit flush operation without a
3527 // list.
3528 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003529 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003530 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003531}
3532
Alexey Bataevb8329262015-02-27 06:33:30 +00003533static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3534 const Expr *X, const Expr *E,
3535 SourceLocation Loc) {
3536 // x = expr;
3537 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003538 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003539 // OpenMP, 2.12.6, atomic Construct
3540 // Any atomic construct with a seq_cst clause forces the atomically
3541 // performed operation to include an implicit flush operation without a
3542 // list.
3543 if (IsSeqCst)
3544 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3545}
3546
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003547static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3548 RValue Update,
3549 BinaryOperatorKind BO,
3550 llvm::AtomicOrdering AO,
3551 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003552 auto &Context = CGF.CGM.getContext();
3553 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003554 // expression is simple and atomic is allowed for the given type for the
3555 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003556 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003557 !Update.getScalarVal()->getType()->isIntegerTy() ||
3558 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3559 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003560 X.getAddress().getElementType())) ||
3561 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003562 !Context.getTargetInfo().hasBuiltinAtomic(
3563 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003564 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003565
3566 llvm::AtomicRMWInst::BinOp RMWOp;
3567 switch (BO) {
3568 case BO_Add:
3569 RMWOp = llvm::AtomicRMWInst::Add;
3570 break;
3571 case BO_Sub:
3572 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003573 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003574 RMWOp = llvm::AtomicRMWInst::Sub;
3575 break;
3576 case BO_And:
3577 RMWOp = llvm::AtomicRMWInst::And;
3578 break;
3579 case BO_Or:
3580 RMWOp = llvm::AtomicRMWInst::Or;
3581 break;
3582 case BO_Xor:
3583 RMWOp = llvm::AtomicRMWInst::Xor;
3584 break;
3585 case BO_LT:
3586 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3587 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3588 : llvm::AtomicRMWInst::Max)
3589 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3590 : llvm::AtomicRMWInst::UMax);
3591 break;
3592 case BO_GT:
3593 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3594 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3595 : llvm::AtomicRMWInst::Min)
3596 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3597 : llvm::AtomicRMWInst::UMin);
3598 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003599 case BO_Assign:
3600 RMWOp = llvm::AtomicRMWInst::Xchg;
3601 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003602 case BO_Mul:
3603 case BO_Div:
3604 case BO_Rem:
3605 case BO_Shl:
3606 case BO_Shr:
3607 case BO_LAnd:
3608 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003609 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003610 case BO_PtrMemD:
3611 case BO_PtrMemI:
3612 case BO_LE:
3613 case BO_GE:
3614 case BO_EQ:
3615 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003616 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003617 case BO_AddAssign:
3618 case BO_SubAssign:
3619 case BO_AndAssign:
3620 case BO_OrAssign:
3621 case BO_XorAssign:
3622 case BO_MulAssign:
3623 case BO_DivAssign:
3624 case BO_RemAssign:
3625 case BO_ShlAssign:
3626 case BO_ShrAssign:
3627 case BO_Comma:
3628 llvm_unreachable("Unsupported atomic update operation");
3629 }
3630 auto *UpdateVal = Update.getScalarVal();
3631 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3632 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003633 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003634 X.getType()->hasSignedIntegerRepresentation());
3635 }
John McCall7f416cc2015-09-08 08:05:57 +00003636 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003637 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003638}
3639
Alexey Bataev5e018f92015-04-23 06:35:10 +00003640std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003641 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3642 llvm::AtomicOrdering AO, SourceLocation Loc,
3643 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3644 // Update expressions are allowed to have the following forms:
3645 // x binop= expr; -> xrval + expr;
3646 // x++, ++x -> xrval + 1;
3647 // x--, --x -> xrval - 1;
3648 // x = x binop expr; -> xrval binop expr
3649 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003650 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3651 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003652 if (X.isGlobalReg()) {
3653 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3654 // 'xrval'.
3655 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3656 } else {
3657 // Perform compare-and-swap procedure.
3658 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003659 }
3660 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003661 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003662}
3663
3664static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3665 const Expr *X, const Expr *E,
3666 const Expr *UE, bool IsXLHSInRHSPart,
3667 SourceLocation Loc) {
3668 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3669 "Update expr in 'atomic update' must be a binary operator.");
3670 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3671 // Update expressions are allowed to have the following forms:
3672 // x binop= expr; -> xrval + expr;
3673 // x++, ++x -> xrval + 1;
3674 // x--, --x -> xrval - 1;
3675 // x = x binop expr; -> xrval binop expr
3676 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003677 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003678 LValue XLValue = CGF.EmitLValue(X);
3679 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003680 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3681 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003682 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3683 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3684 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3685 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3686 auto Gen =
3687 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3688 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3689 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3690 return CGF.EmitAnyExpr(UE);
3691 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003692 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3693 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3694 // OpenMP, 2.12.6, atomic Construct
3695 // Any atomic construct with a seq_cst clause forces the atomically
3696 // performed operation to include an implicit flush operation without a
3697 // list.
3698 if (IsSeqCst)
3699 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3700}
3701
3702static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003703 QualType SourceType, QualType ResType,
3704 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003705 switch (CGF.getEvaluationKind(ResType)) {
3706 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003707 return RValue::get(
3708 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003709 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003710 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003711 return RValue::getComplex(Res.first, Res.second);
3712 }
3713 case TEK_Aggregate:
3714 break;
3715 }
3716 llvm_unreachable("Must be a scalar or complex.");
3717}
3718
3719static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3720 bool IsPostfixUpdate, const Expr *V,
3721 const Expr *X, const Expr *E,
3722 const Expr *UE, bool IsXLHSInRHSPart,
3723 SourceLocation Loc) {
3724 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3725 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3726 RValue NewVVal;
3727 LValue VLValue = CGF.EmitLValue(V);
3728 LValue XLValue = CGF.EmitLValue(X);
3729 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003730 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3731 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003732 QualType NewVValType;
3733 if (UE) {
3734 // 'x' is updated with some additional value.
3735 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3736 "Update expr in 'atomic capture' must be a binary operator.");
3737 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3738 // Update expressions are allowed to have the following forms:
3739 // x binop= expr; -> xrval + expr;
3740 // x++, ++x -> xrval + 1;
3741 // x--, --x -> xrval - 1;
3742 // x = x binop expr; -> xrval binop expr
3743 // x = expr Op x; - > expr binop xrval;
3744 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3745 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3746 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3747 NewVValType = XRValExpr->getType();
3748 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3749 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003750 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003751 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3752 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3753 RValue Res = CGF.EmitAnyExpr(UE);
3754 NewVVal = IsPostfixUpdate ? XRValue : Res;
3755 return Res;
3756 };
3757 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3758 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3759 if (Res.first) {
3760 // 'atomicrmw' instruction was generated.
3761 if (IsPostfixUpdate) {
3762 // Use old value from 'atomicrmw'.
3763 NewVVal = Res.second;
3764 } else {
3765 // 'atomicrmw' does not provide new value, so evaluate it using old
3766 // value of 'x'.
3767 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3768 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3769 NewVVal = CGF.EmitAnyExpr(UE);
3770 }
3771 }
3772 } else {
3773 // 'x' is simply rewritten with some 'expr'.
3774 NewVValType = X->getType().getNonReferenceType();
3775 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003776 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003777 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003778 NewVVal = XRValue;
3779 return ExprRValue;
3780 };
3781 // Try to perform atomicrmw xchg, otherwise simple exchange.
3782 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3783 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3784 Loc, Gen);
3785 if (Res.first) {
3786 // 'atomicrmw' instruction was generated.
3787 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3788 }
3789 }
3790 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003791 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003792 // OpenMP, 2.12.6, atomic Construct
3793 // Any atomic construct with a seq_cst clause forces the atomically
3794 // performed operation to include an implicit flush operation without a
3795 // list.
3796 if (IsSeqCst)
3797 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3798}
3799
Alexey Bataevb57056f2015-01-22 06:17:56 +00003800static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003801 bool IsSeqCst, bool IsPostfixUpdate,
3802 const Expr *X, const Expr *V, const Expr *E,
3803 const Expr *UE, bool IsXLHSInRHSPart,
3804 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003805 switch (Kind) {
3806 case OMPC_read:
3807 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3808 break;
3809 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003810 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3811 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003812 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003813 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003814 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3815 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003816 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003817 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3818 IsXLHSInRHSPart, Loc);
3819 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003820 case OMPC_if:
3821 case OMPC_final:
3822 case OMPC_num_threads:
3823 case OMPC_private:
3824 case OMPC_firstprivate:
3825 case OMPC_lastprivate:
3826 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003827 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003828 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003829 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003830 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003831 case OMPC_collapse:
3832 case OMPC_default:
3833 case OMPC_seq_cst:
3834 case OMPC_shared:
3835 case OMPC_linear:
3836 case OMPC_aligned:
3837 case OMPC_copyin:
3838 case OMPC_copyprivate:
3839 case OMPC_flush:
3840 case OMPC_proc_bind:
3841 case OMPC_schedule:
3842 case OMPC_ordered:
3843 case OMPC_nowait:
3844 case OMPC_untied:
3845 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003846 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003847 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003848 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003849 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003850 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003851 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003852 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003853 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003854 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003855 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003856 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003857 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003858 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003859 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003860 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003861 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003862 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003863 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003864 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003865 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003866 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3867 }
3868}
3869
3870void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003871 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003872 OpenMPClauseKind Kind = OMPC_unknown;
3873 for (auto *C : S.clauses()) {
3874 // Find first clause (skip seq_cst clause, if it is first).
3875 if (C->getClauseKind() != OMPC_seq_cst) {
3876 Kind = C->getClauseKind();
3877 break;
3878 }
3879 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003880
3881 const auto *CS =
3882 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003883 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003884 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003885 }
3886 // Processing for statements under 'atomic capture'.
3887 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3888 for (const auto *C : Compound->body()) {
3889 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3890 enterFullExpression(EWC);
3891 }
3892 }
3893 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003894
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003895 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3896 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003897 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003898 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3899 S.getV(), S.getExpr(), S.getUpdateExpr(),
3900 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003901 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003902 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003903 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003904}
3905
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003906static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3907 const OMPExecutableDirective &S,
3908 const RegionCodeGenTy &CodeGen) {
3909 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3910 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003911 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003912
Samuel Antaoee8fb302016-01-06 13:42:12 +00003913 llvm::Function *Fn = nullptr;
3914 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003915
Samuel Antaobed3c462015-10-02 16:14:20 +00003916 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003917 // Check for the at most one if clause associated with the target region.
3918 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3919 if (C->getNameModifier() == OMPD_unknown ||
3920 C->getNameModifier() == OMPD_target) {
3921 IfCond = C->getCondition();
3922 break;
3923 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003924 }
3925
3926 // Check if we have any device clause associated with the directive.
3927 const Expr *Device = nullptr;
3928 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3929 Device = C->getDevice();
3930 }
3931
Samuel Antaoee8fb302016-01-06 13:42:12 +00003932 // Check if we have an if clause whose conditional always evaluates to false
3933 // or if we do not have any targets specified. If so the target region is not
3934 // an offload entry point.
3935 bool IsOffloadEntry = true;
3936 if (IfCond) {
3937 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003938 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003939 IsOffloadEntry = false;
3940 }
3941 if (CGM.getLangOpts().OMPTargetTriples.empty())
3942 IsOffloadEntry = false;
3943
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003944 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003945 StringRef ParentName;
3946 // In case we have Ctors/Dtors we use the complete type variant to produce
3947 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003948 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003949 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003950 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003951 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3952 else
3953 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003954 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003955
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003956 // Emit target region as a standalone region.
3957 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3958 IsOffloadEntry, CodeGen);
3959 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003960 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3961 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003962 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003963 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003964}
3965
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003966static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3967 PrePostActionTy &Action) {
3968 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3969 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3970 CGF.EmitOMPPrivateClause(S, PrivateScope);
3971 (void)PrivateScope.Privatize();
3972
3973 Action.Enter(CGF);
3974 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3975}
3976
3977void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3978 StringRef ParentName,
3979 const OMPTargetDirective &S) {
3980 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3981 emitTargetRegion(CGF, S, Action);
3982 };
3983 llvm::Function *Fn;
3984 llvm::Constant *Addr;
3985 // Emit target region as a standalone region.
3986 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3987 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3988 assert(Fn && Addr && "Target device function emission failed.");
3989}
3990
3991void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3992 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3993 emitTargetRegion(CGF, S, Action);
3994 };
3995 emitCommonOMPTargetDirective(*this, S, CodeGen);
3996}
3997
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003998static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3999 const OMPExecutableDirective &S,
4000 OpenMPDirectiveKind InnermostKind,
4001 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004002 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4003 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4004 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004005
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004006 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4007 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004008 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004009 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4010 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004011
Carlo Bertollic6872252016-04-04 15:55:02 +00004012 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4013 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004014 }
4015
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004016 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004017 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4018 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004019 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4020 CapturedVars);
4021}
4022
4023void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004024 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004025 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004026 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004027 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4028 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004030 (void)PrivateScope.Privatize();
4031 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004032 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004033 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004034 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004035 emitPostUpdateForReductionClause(
4036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004037}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004038
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004039static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4040 const OMPTargetTeamsDirective &S) {
4041 auto *CS = S.getCapturedStmt(OMPD_teams);
4042 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004043 // Emit teams region as a standalone region.
4044 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4045 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4046 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4047 CGF.EmitOMPPrivateClause(S, PrivateScope);
4048 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4049 (void)PrivateScope.Privatize();
4050 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004051 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004052 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004053 };
4054 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004055 emitPostUpdateForReductionClause(
4056 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004057}
4058
4059void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4060 CodeGenModule &CGM, StringRef ParentName,
4061 const OMPTargetTeamsDirective &S) {
4062 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4063 emitTargetTeamsRegion(CGF, Action, S);
4064 };
4065 llvm::Function *Fn;
4066 llvm::Constant *Addr;
4067 // Emit target region as a standalone region.
4068 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4069 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4070 assert(Fn && Addr && "Target device function emission failed.");
4071}
4072
4073void CodeGenFunction::EmitOMPTargetTeamsDirective(
4074 const OMPTargetTeamsDirective &S) {
4075 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4076 emitTargetTeamsRegion(CGF, Action, S);
4077 };
4078 emitCommonOMPTargetDirective(*this, S, CodeGen);
4079}
4080
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004081static void
4082emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4083 const OMPTargetTeamsDistributeDirective &S) {
4084 Action.Enter(CGF);
4085 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4086 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4087 };
4088
4089 // Emit teams region as a standalone region.
4090 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4091 PrePostActionTy &) {
4092 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4093 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4094 (void)PrivateScope.Privatize();
4095 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4096 CodeGenDistribute);
4097 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4098 };
4099 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4100 emitPostUpdateForReductionClause(CGF, S,
4101 [](CodeGenFunction &) { return nullptr; });
4102}
4103
4104void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4105 CodeGenModule &CGM, StringRef ParentName,
4106 const OMPTargetTeamsDistributeDirective &S) {
4107 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4108 emitTargetTeamsDistributeRegion(CGF, Action, S);
4109 };
4110 llvm::Function *Fn;
4111 llvm::Constant *Addr;
4112 // Emit target region as a standalone region.
4113 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4114 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4115 assert(Fn && Addr && "Target device function emission failed.");
4116}
4117
4118void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4119 const OMPTargetTeamsDistributeDirective &S) {
4120 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4121 emitTargetTeamsDistributeRegion(CGF, Action, S);
4122 };
4123 emitCommonOMPTargetDirective(*this, S, CodeGen);
4124}
4125
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004126static void emitTargetTeamsDistributeSimdRegion(
4127 CodeGenFunction &CGF, PrePostActionTy &Action,
4128 const OMPTargetTeamsDistributeSimdDirective &S) {
4129 Action.Enter(CGF);
4130 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4131 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4132 };
4133
4134 // Emit teams region as a standalone region.
4135 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4136 PrePostActionTy &) {
4137 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4138 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4139 (void)PrivateScope.Privatize();
4140 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4141 CodeGenDistribute);
4142 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4143 };
4144 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4145 emitPostUpdateForReductionClause(CGF, S,
4146 [](CodeGenFunction &) { return nullptr; });
4147}
4148
4149void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4150 CodeGenModule &CGM, StringRef ParentName,
4151 const OMPTargetTeamsDistributeSimdDirective &S) {
4152 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4153 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4154 };
4155 llvm::Function *Fn;
4156 llvm::Constant *Addr;
4157 // Emit target region as a standalone region.
4158 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4159 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4160 assert(Fn && Addr && "Target device function emission failed.");
4161}
4162
4163void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4164 const OMPTargetTeamsDistributeSimdDirective &S) {
4165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4166 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4167 };
4168 emitCommonOMPTargetDirective(*this, S, CodeGen);
4169}
4170
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004171void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4172 const OMPTeamsDistributeDirective &S) {
4173
4174 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4175 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4176 };
4177
4178 // Emit teams region as a standalone region.
4179 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4180 PrePostActionTy &) {
4181 OMPPrivateScope PrivateScope(CGF);
4182 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4183 (void)PrivateScope.Privatize();
4184 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4185 CodeGenDistribute);
4186 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4187 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004188 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004189 emitPostUpdateForReductionClause(*this, S,
4190 [](CodeGenFunction &) { return nullptr; });
4191}
4192
Alexey Bataev999277a2017-12-06 14:31:09 +00004193void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4194 const OMPTeamsDistributeSimdDirective &S) {
4195 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4196 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4197 };
4198
4199 // Emit teams region as a standalone region.
4200 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4201 PrePostActionTy &) {
4202 OMPPrivateScope PrivateScope(CGF);
4203 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4204 (void)PrivateScope.Privatize();
4205 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4206 CodeGenDistribute);
4207 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4208 };
4209 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4210 emitPostUpdateForReductionClause(*this, S,
4211 [](CodeGenFunction &) { return nullptr; });
4212}
4213
Carlo Bertolli62fae152017-11-20 20:46:39 +00004214void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4215 const OMPTeamsDistributeParallelForDirective &S) {
4216 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4217 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4218 S.getDistInc());
4219 };
4220
4221 // Emit teams region as a standalone region.
4222 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4223 PrePostActionTy &) {
4224 OMPPrivateScope PrivateScope(CGF);
4225 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4226 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004227 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4228 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004229 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4230 };
4231 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4232 emitPostUpdateForReductionClause(*this, S,
4233 [](CodeGenFunction &) { return nullptr; });
4234}
4235
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004236void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4237 const OMPTeamsDistributeParallelForSimdDirective &S) {
4238 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4239 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4240 S.getDistInc());
4241 };
4242
4243 // Emit teams region as a standalone region.
4244 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4245 PrePostActionTy &) {
4246 OMPPrivateScope PrivateScope(CGF);
4247 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4248 (void)PrivateScope.Privatize();
4249 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4250 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4251 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4252 };
4253 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4254 emitPostUpdateForReductionClause(*this, S,
4255 [](CodeGenFunction &) { return nullptr; });
4256}
4257
Carlo Bertolli52978c32018-01-03 21:12:44 +00004258static void emitTargetTeamsDistributeParallelForRegion(
4259 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4260 PrePostActionTy &Action) {
4261 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4262 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4263 S.getDistInc());
4264 };
4265
4266 // Emit teams region as a standalone region.
4267 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4268 PrePostActionTy &) {
4269 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4270 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4271 (void)PrivateScope.Privatize();
4272 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4273 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4274 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4275 };
4276
4277 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4278 CodeGenTeams);
4279 emitPostUpdateForReductionClause(CGF, S,
4280 [](CodeGenFunction &) { return nullptr; });
4281}
4282
4283void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4284 CodeGenModule &CGM, StringRef ParentName,
4285 const OMPTargetTeamsDistributeParallelForDirective &S) {
4286 // Emit SPMD target teams distribute parallel for region as a standalone
4287 // region.
4288 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4289 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4290 };
4291 llvm::Function *Fn;
4292 llvm::Constant *Addr;
4293 // Emit target region as a standalone region.
4294 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4295 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4296 assert(Fn && Addr && "Target device function emission failed.");
4297}
4298
4299void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4300 const OMPTargetTeamsDistributeParallelForDirective &S) {
4301 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4302 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4303 };
4304 emitCommonOMPTargetDirective(*this, S, CodeGen);
4305}
4306
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004307void CodeGenFunction::EmitOMPCancellationPointDirective(
4308 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004309 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4310 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004311}
4312
Alexey Bataev80909872015-07-02 11:25:17 +00004313void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004314 const Expr *IfCond = nullptr;
4315 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4316 if (C->getNameModifier() == OMPD_unknown ||
4317 C->getNameModifier() == OMPD_cancel) {
4318 IfCond = C->getCondition();
4319 break;
4320 }
4321 }
4322 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004323 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004324}
4325
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004326CodeGenFunction::JumpDest
4327CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004328 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4329 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004330 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004331 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004332 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4333 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004334 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004335 Kind == OMPD_teams_distribute_parallel_for ||
4336 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004337 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004338}
Michael Wong65f367f2015-07-21 13:44:28 +00004339
Samuel Antaocc10b852016-07-28 14:23:26 +00004340void CodeGenFunction::EmitOMPUseDevicePtrClause(
4341 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4342 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4343 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4344 auto OrigVarIt = C.varlist_begin();
4345 auto InitIt = C.inits().begin();
4346 for (auto PvtVarIt : C.private_copies()) {
4347 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4348 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4349 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4350
4351 // In order to identify the right initializer we need to match the
4352 // declaration used by the mapping logic. In some cases we may get
4353 // OMPCapturedExprDecl that refers to the original declaration.
4354 const ValueDecl *MatchingVD = OrigVD;
4355 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4356 // OMPCapturedExprDecl are used to privative fields of the current
4357 // structure.
4358 auto *ME = cast<MemberExpr>(OED->getInit());
4359 assert(isa<CXXThisExpr>(ME->getBase()) &&
4360 "Base should be the current struct!");
4361 MatchingVD = ME->getMemberDecl();
4362 }
4363
4364 // If we don't have information about the current list item, move on to
4365 // the next one.
4366 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4367 if (InitAddrIt == CaptureDeviceAddrMap.end())
4368 continue;
4369
4370 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4371 // Initialize the temporary initialization variable with the address we
4372 // get from the runtime library. We have to cast the source address
4373 // because it is always a void *. References are materialized in the
4374 // privatization scope, so the initialization here disregards the fact
4375 // the original variable is a reference.
4376 QualType AddrQTy =
4377 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4378 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4379 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4380 setAddrOfLocalVar(InitVD, InitAddr);
4381
4382 // Emit private declaration, it will be initialized by the value we
4383 // declaration we just added to the local declarations map.
4384 EmitDecl(*PvtVD);
4385
4386 // The initialization variables reached its purpose in the emission
4387 // ofthe previous declaration, so we don't need it anymore.
4388 LocalDeclMap.erase(InitVD);
4389
4390 // Return the address of the private variable.
4391 return GetAddrOfLocalVar(PvtVD);
4392 });
4393 assert(IsRegistered && "firstprivate var already registered as private");
4394 // Silence the warning about unused variable.
4395 (void)IsRegistered;
4396
4397 ++OrigVarIt;
4398 ++InitIt;
4399 }
4400}
4401
Michael Wong65f367f2015-07-21 13:44:28 +00004402// Generate the instructions for '#pragma omp target data' directive.
4403void CodeGenFunction::EmitOMPTargetDataDirective(
4404 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004405 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4406
4407 // Create a pre/post action to signal the privatization of the device pointer.
4408 // This action can be replaced by the OpenMP runtime code generation to
4409 // deactivate privatization.
4410 bool PrivatizeDevicePointers = false;
4411 class DevicePointerPrivActionTy : public PrePostActionTy {
4412 bool &PrivatizeDevicePointers;
4413
4414 public:
4415 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4416 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4417 void Enter(CodeGenFunction &CGF) override {
4418 PrivatizeDevicePointers = true;
4419 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004420 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004421 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4422
4423 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4424 CodeGenFunction &CGF, PrePostActionTy &Action) {
4425 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4426 CGF.EmitStmt(
4427 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4428 };
4429
4430 // Codegen that selects wheather to generate the privatization code or not.
4431 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4432 &InnermostCodeGen](CodeGenFunction &CGF,
4433 PrePostActionTy &Action) {
4434 RegionCodeGenTy RCG(InnermostCodeGen);
4435 PrivatizeDevicePointers = false;
4436
4437 // Call the pre-action to change the status of PrivatizeDevicePointers if
4438 // needed.
4439 Action.Enter(CGF);
4440
4441 if (PrivatizeDevicePointers) {
4442 OMPPrivateScope PrivateScope(CGF);
4443 // Emit all instances of the use_device_ptr clause.
4444 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4445 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4446 Info.CaptureDeviceAddrMap);
4447 (void)PrivateScope.Privatize();
4448 RCG(CGF);
4449 } else
4450 RCG(CGF);
4451 };
4452
4453 // Forward the provided action to the privatization codegen.
4454 RegionCodeGenTy PrivRCG(PrivCodeGen);
4455 PrivRCG.setAction(Action);
4456
4457 // Notwithstanding the body of the region is emitted as inlined directive,
4458 // we don't use an inline scope as changes in the references inside the
4459 // region are expected to be visible outside, so we do not privative them.
4460 OMPLexicalScope Scope(CGF, S);
4461 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4462 PrivRCG);
4463 };
4464
4465 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004466
4467 // If we don't have target devices, don't bother emitting the data mapping
4468 // code.
4469 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004470 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004471 return;
4472 }
4473
4474 // Check if we have any if clause associated with the directive.
4475 const Expr *IfCond = nullptr;
4476 if (auto *C = S.getSingleClause<OMPIfClause>())
4477 IfCond = C->getCondition();
4478
4479 // Check if we have any device clause associated with the directive.
4480 const Expr *Device = nullptr;
4481 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4482 Device = C->getDevice();
4483
Samuel Antaocc10b852016-07-28 14:23:26 +00004484 // Set the action to signal privatization of device pointers.
4485 RCG.setAction(PrivAction);
4486
4487 // Emit region code.
4488 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4489 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004490}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004491
Samuel Antaodf67fc42016-01-19 19:15:56 +00004492void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4493 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004494 // If we don't have target devices, don't bother emitting the data mapping
4495 // code.
4496 if (CGM.getLangOpts().OMPTargetTriples.empty())
4497 return;
4498
4499 // Check if we have any if clause associated with the directive.
4500 const Expr *IfCond = nullptr;
4501 if (auto *C = S.getSingleClause<OMPIfClause>())
4502 IfCond = C->getCondition();
4503
4504 // Check if we have any device clause associated with the directive.
4505 const Expr *Device = nullptr;
4506 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4507 Device = C->getDevice();
4508
Alexey Bataev7828b252017-11-21 17:08:48 +00004509 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004510 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004511}
4512
Samuel Antao72590762016-01-19 20:04:50 +00004513void CodeGenFunction::EmitOMPTargetExitDataDirective(
4514 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004515 // If we don't have target devices, don't bother emitting the data mapping
4516 // code.
4517 if (CGM.getLangOpts().OMPTargetTriples.empty())
4518 return;
4519
4520 // Check if we have any if clause associated with the directive.
4521 const Expr *IfCond = nullptr;
4522 if (auto *C = S.getSingleClause<OMPIfClause>())
4523 IfCond = C->getCondition();
4524
4525 // Check if we have any device clause associated with the directive.
4526 const Expr *Device = nullptr;
4527 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4528 Device = C->getDevice();
4529
Alexey Bataev7828b252017-11-21 17:08:48 +00004530 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004531 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004532}
4533
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004534static void emitTargetParallelRegion(CodeGenFunction &CGF,
4535 const OMPTargetParallelDirective &S,
4536 PrePostActionTy &Action) {
4537 // Get the captured statement associated with the 'parallel' region.
4538 auto *CS = S.getCapturedStmt(OMPD_parallel);
4539 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004540 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4541 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4542 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4543 CGF.EmitOMPPrivateClause(S, PrivateScope);
4544 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4545 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004546 // TODO: Add support for clauses.
4547 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004548 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004549 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004550 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4551 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004552 emitPostUpdateForReductionClause(
4553 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004554}
4555
4556void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4557 CodeGenModule &CGM, StringRef ParentName,
4558 const OMPTargetParallelDirective &S) {
4559 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4560 emitTargetParallelRegion(CGF, S, Action);
4561 };
4562 llvm::Function *Fn;
4563 llvm::Constant *Addr;
4564 // Emit target region as a standalone region.
4565 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4566 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4567 assert(Fn && Addr && "Target device function emission failed.");
4568}
4569
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004570void CodeGenFunction::EmitOMPTargetParallelDirective(
4571 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004572 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4573 emitTargetParallelRegion(CGF, S, Action);
4574 };
4575 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004576}
4577
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004578static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4579 const OMPTargetParallelForDirective &S,
4580 PrePostActionTy &Action) {
4581 Action.Enter(CGF);
4582 // Emit directive as a combined directive that consists of two implicit
4583 // directives: 'parallel' with 'for' directive.
4584 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004585 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4586 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004587 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4588 emitDispatchForLoopBounds);
4589 };
4590 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4591 emitEmptyBoundParameters);
4592}
4593
4594void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4595 CodeGenModule &CGM, StringRef ParentName,
4596 const OMPTargetParallelForDirective &S) {
4597 // Emit SPMD target parallel for region as a standalone region.
4598 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4599 emitTargetParallelForRegion(CGF, S, Action);
4600 };
4601 llvm::Function *Fn;
4602 llvm::Constant *Addr;
4603 // Emit target region as a standalone region.
4604 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4605 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4606 assert(Fn && Addr && "Target device function emission failed.");
4607}
4608
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004609void CodeGenFunction::EmitOMPTargetParallelForDirective(
4610 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004611 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4612 emitTargetParallelForRegion(CGF, S, Action);
4613 };
4614 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004615}
4616
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004617static void
4618emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4619 const OMPTargetParallelForSimdDirective &S,
4620 PrePostActionTy &Action) {
4621 Action.Enter(CGF);
4622 // Emit directive as a combined directive that consists of two implicit
4623 // directives: 'parallel' with 'for' directive.
4624 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4625 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4626 emitDispatchForLoopBounds);
4627 };
4628 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4629 emitEmptyBoundParameters);
4630}
4631
4632void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4633 CodeGenModule &CGM, StringRef ParentName,
4634 const OMPTargetParallelForSimdDirective &S) {
4635 // Emit SPMD target parallel for region as a standalone region.
4636 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4637 emitTargetParallelForSimdRegion(CGF, S, Action);
4638 };
4639 llvm::Function *Fn;
4640 llvm::Constant *Addr;
4641 // Emit target region as a standalone region.
4642 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4643 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4644 assert(Fn && Addr && "Target device function emission failed.");
4645}
4646
4647void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4648 const OMPTargetParallelForSimdDirective &S) {
4649 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4650 emitTargetParallelForSimdRegion(CGF, S, Action);
4651 };
4652 emitCommonOMPTargetDirective(*this, S, CodeGen);
4653}
4654
Alexey Bataev7292c292016-04-25 12:22:29 +00004655/// Emit a helper variable and return corresponding lvalue.
4656static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4657 const ImplicitParamDecl *PVD,
4658 CodeGenFunction::OMPPrivateScope &Privates) {
4659 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4660 Privates.addPrivate(
4661 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4662}
4663
4664void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4665 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4666 // Emit outlined function for task construct.
4667 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4668 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4669 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4670 const Expr *IfCond = nullptr;
4671 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4672 if (C->getNameModifier() == OMPD_unknown ||
4673 C->getNameModifier() == OMPD_taskloop) {
4674 IfCond = C->getCondition();
4675 break;
4676 }
4677 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004678
4679 OMPTaskDataTy Data;
4680 // Check if taskloop must be emitted without taskgroup.
4681 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004682 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004683 Data.Tied = true;
4684 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004685 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4686 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004687 Data.Schedule.setInt(/*IntVal=*/false);
4688 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004689 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4690 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004691 Data.Schedule.setInt(/*IntVal=*/true);
4692 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004693 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004694
4695 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4696 // if (PreCond) {
4697 // for (IV in 0..LastIteration) BODY;
4698 // <Final counter/linear vars updates>;
4699 // }
4700 //
4701
4702 // Emit: if (PreCond) - begin.
4703 // If the condition constant folds and can be elided, avoid emitting the
4704 // whole loop.
4705 bool CondConstant;
4706 llvm::BasicBlock *ContBlock = nullptr;
4707 OMPLoopScope PreInitScope(CGF, S);
4708 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4709 if (!CondConstant)
4710 return;
4711 } else {
4712 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4713 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4714 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4715 CGF.getProfileCount(&S));
4716 CGF.EmitBlock(ThenBlock);
4717 CGF.incrementProfileCounter(&S);
4718 }
4719
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004720 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4721 CGF.EmitOMPSimdInit(S);
4722
Alexey Bataev7292c292016-04-25 12:22:29 +00004723 OMPPrivateScope LoopScope(CGF);
4724 // Emit helper vars inits.
4725 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4726 auto *I = CS->getCapturedDecl()->param_begin();
4727 auto *LBP = std::next(I, LowerBound);
4728 auto *UBP = std::next(I, UpperBound);
4729 auto *STP = std::next(I, Stride);
4730 auto *LIP = std::next(I, LastIter);
4731 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4732 LoopScope);
4733 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4734 LoopScope);
4735 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4736 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4737 LoopScope);
4738 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004739 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004740 (void)LoopScope.Privatize();
4741 // Emit the loop iteration variable.
4742 const Expr *IVExpr = S.getIterationVariable();
4743 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4744 CGF.EmitVarDecl(*IVDecl);
4745 CGF.EmitIgnoredExpr(S.getInit());
4746
4747 // Emit the iterations count variable.
4748 // If it is not a variable, Sema decided to calculate iterations count on
4749 // each iteration (e.g., it is foldable into a constant).
4750 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4751 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4752 // Emit calculation of the iterations count.
4753 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4754 }
4755
4756 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4757 S.getInc(),
4758 [&S](CodeGenFunction &CGF) {
4759 CGF.EmitOMPLoopBody(S, JumpDest());
4760 CGF.EmitStopPoint(&S);
4761 },
4762 [](CodeGenFunction &) {});
4763 // Emit: if (PreCond) - end.
4764 if (ContBlock) {
4765 CGF.EmitBranch(ContBlock);
4766 CGF.EmitBlock(ContBlock, true);
4767 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004768 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4769 if (HasLastprivateClause) {
4770 CGF.EmitOMPLastprivateClauseFinal(
4771 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4772 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4773 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4774 (*LIP)->getType(), S.getLocStart())));
4775 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004776 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004777 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4778 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4779 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004780 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4781 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004782 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4783 OutlinedFn, SharedsTy,
4784 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004785 };
4786 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4787 CodeGen);
4788 };
Alexey Bataev33446032017-07-12 18:09:32 +00004789 if (Data.Nogroup)
4790 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4791 else {
4792 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4793 *this,
4794 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4795 PrePostActionTy &Action) {
4796 Action.Enter(CGF);
4797 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4798 },
4799 S.getLocStart());
4800 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004801}
4802
Alexey Bataev49f6e782015-12-01 04:18:41 +00004803void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004804 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004805}
4806
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004807void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4808 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004809 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004810}
Samuel Antao686c70c2016-05-26 17:30:50 +00004811
4812// Generate the instructions for '#pragma omp target update' directive.
4813void CodeGenFunction::EmitOMPTargetUpdateDirective(
4814 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004815 // If we don't have target devices, don't bother emitting the data mapping
4816 // code.
4817 if (CGM.getLangOpts().OMPTargetTriples.empty())
4818 return;
4819
4820 // Check if we have any if clause associated with the directive.
4821 const Expr *IfCond = nullptr;
4822 if (auto *C = S.getSingleClause<OMPIfClause>())
4823 IfCond = C->getCondition();
4824
4825 // Check if we have any device clause associated with the directive.
4826 const Expr *Device = nullptr;
4827 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4828 Device = C->getDevice();
4829
Alexey Bataev7828b252017-11-21 17:08:48 +00004830 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004831 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004832}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004833
4834void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4835 const OMPExecutableDirective &D) {
4836 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4837 return;
4838 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4839 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4840 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4841 } else {
4842 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4843 for (const auto *E : LD->counters()) {
4844 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4845 cast<DeclRefExpr>(E)->getDecl())) {
4846 // Emit only those that were not explicitly referenced in clauses.
4847 if (!CGF.LocalDeclMap.count(VD))
4848 CGF.EmitVarDecl(*VD);
4849 }
4850 }
4851 }
4852 const auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
4853 while (const auto *CCS = dyn_cast<CapturedStmt>(CS->getCapturedStmt()))
4854 CS = CCS;
4855 CGF.EmitStmt(CS->getCapturedStmt());
4856 }
4857 };
4858 OMPSimdLexicalScope Scope(*this, D);
4859 CGM.getOpenMPRuntime().emitInlinedDirective(
4860 *this,
4861 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4862 : D.getDirectiveKind(),
4863 CodeGen);
4864}