blob: c6a0cdb5a5498ef84f9eda9d5e42b3d5f4130943 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
69 for (auto &C : CS->captures()) {
70 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
75 const_cast<VarDecl *>(VD),
76 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
78 VD->getType().getNonReferenceType(), VK_LValue, SourceLocation());
79 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80 return CGF.EmitLValue(&DRE).getAddress();
81 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000123 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
126 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
127 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
128 });
129 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000130 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000131 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
132 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
133 for (const auto *I : PreInits->decls())
134 CGF.EmitVarDecl(cast<VarDecl>(*I));
135 }
136 }
137 }
138
139public:
140 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
141 : CodeGenFunction::RunCleanupsScope(CGF) {
142 emitPreInitStmt(CGF, S);
143 }
144};
145
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000146class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
147 CodeGenFunction::OMPPrivateScope InlinedShareds;
148
149 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
150 return CGF.LambdaCaptureFields.lookup(VD) ||
151 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
152 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
153 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
154 }
155
156public:
157 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
159 InlinedShareds(CGF) {
160 for (const auto *C : S.clauses()) {
161 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
162 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
163 for (const auto *I : PreInit->decls()) {
164 if (!I->hasAttr<OMPCaptureNoInitAttr>())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
166 else {
167 CodeGenFunction::AutoVarEmission Emission =
168 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
169 CGF.EmitAutoVarCleanups(Emission);
170 }
171 }
172 }
173 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
174 for (const Expr *E : UDP->varlists()) {
175 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
176 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
177 CGF.EmitVarDecl(*OED);
178 }
179 }
180 }
181 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
182 CGF.EmitOMPPrivateClause(S, InlinedShareds);
183 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
184 if (const Expr *E = TG->getReductionRef())
185 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
186 }
187 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
188 while (CS) {
189 for (auto &C : CS->captures()) {
190 if (C.capturesVariable() || C.capturesVariableByCopy()) {
191 auto *VD = C.getCapturedVar();
192 assert(VD == VD->getCanonicalDecl() &&
193 "Canonical decl must be captured.");
194 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
195 isCapturedVar(CGF, VD) ||
196 (CGF.CapturedStmtInfo &&
197 InlinedShareds.isGlobalVarCaptured(VD)),
198 VD->getType().getNonReferenceType(), VK_LValue,
199 SourceLocation());
200 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
201 return CGF.EmitLValue(&DRE).getAddress();
202 });
203 }
204 }
205 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
206 }
207 (void)InlinedShareds.Privatize();
208 }
209};
210
Alexey Bataev3392d762016-02-16 11:18:12 +0000211} // namespace
212
Alexey Bataevf8365372017-11-17 17:57:25 +0000213static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
214 const OMPExecutableDirective &S,
215 const RegionCodeGenTy &CodeGen);
216
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000217LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
218 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
220 OrigVD = OrigVD->getCanonicalDecl();
221 bool IsCaptured =
222 LambdaCaptureFields.lookup(OrigVD) ||
223 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
224 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
226 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
227 return EmitLValue(&DRE);
228 }
229 }
230 return EmitLValue(E);
231}
232
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
234 auto &C = getContext();
235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
239 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
240 llvm::Value *ArraySize;
241 std::tie(ArraySize, Ty) = getVLASize(VAT);
242 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
243 }
244 SizeInChars = C.getTypeSizeInChars(Ty);
245 if (SizeInChars.isZero())
246 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
247 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
248 } else
249 Size = CGM.getSize(SizeInChars);
250 return Size;
251}
252
Alexey Bataev2377fe92015-09-10 08:12:02 +0000253void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000254 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000255 const RecordDecl *RD = S.getCapturedRecordDecl();
256 auto CurField = RD->field_begin();
257 auto CurCap = S.captures().begin();
258 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
259 E = S.capture_init_end();
260 I != E; ++I, ++CurField, ++CurCap) {
261 if (CurField->hasCapturedVLAType()) {
262 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000263 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000264 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000265 } else if (CurCap->capturesThis())
266 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000267 else if (CurCap->capturesVariableByCopy()) {
268 llvm::Value *CV =
269 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
270
271 // If the field is not a pointer, we need to save the actual value
272 // and load it as a void pointer.
273 if (!CurField->getType()->isAnyPointerType()) {
274 auto &Ctx = getContext();
275 auto DstAddr = CreateMemTemp(
276 Ctx.getUIntPtrType(),
277 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
278 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
279
280 auto *SrcAddrVal = EmitScalarConversion(
281 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
282 Ctx.getPointerType(CurField->getType()), SourceLocation());
283 LValue SrcLV =
284 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
285
286 // Store the value using the source type pointer.
287 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
288
289 // Load the value using the destination type pointer.
290 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
291 }
292 CapturedVars.push_back(CV);
293 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000296 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 }
298}
299
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000300static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
301 StringRef Name, LValue AddrLV,
302 bool isReferenceType = false) {
303 ASTContext &Ctx = CGF.getContext();
304
305 auto *CastedPtr = CGF.EmitScalarConversion(
306 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
307 Ctx.getPointerType(DstType), SourceLocation());
308 auto TmpAddr =
309 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
310 .getAddress();
311
312 // If we are dealing with references we need to return the address of the
313 // reference instead of the reference of the value.
314 if (isReferenceType) {
315 QualType RefType = Ctx.getLValueReferenceType(DstType);
316 auto *RefVal = TmpAddr.getPointer();
317 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
318 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000319 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000320 }
321
322 return TmpAddr;
323}
324
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000325static QualType getCanonicalParamType(ASTContext &C, QualType T) {
326 if (T->isLValueReferenceType()) {
327 return C.getLValueReferenceType(
328 getCanonicalParamType(C, T.getNonReferenceType()),
329 /*SpelledAsLValue=*/false);
330 }
331 if (T->isPointerType())
332 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000333 if (auto *A = T->getAsArrayTypeUnsafe()) {
334 if (auto *VLA = dyn_cast<VariableArrayType>(A))
335 return getCanonicalParamType(C, VLA->getElementType());
336 else if (!A->isVariablyModifiedType())
337 return C.getCanonicalType(T);
338 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000339 return C.getCanonicalParamType(T);
340}
341
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000342namespace {
343 /// Contains required data for proper outlined function codegen.
344 struct FunctionOptions {
345 /// Captured statement for which the function is generated.
346 const CapturedStmt *S = nullptr;
347 /// true if cast to/from UIntPtr is required for variables captured by
348 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000349 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000350 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000351 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000352 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000353 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000354 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000355 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
356 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000357 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000358 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
359 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000360 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000361 };
362}
363
Alexey Bataeve754b182017-08-09 19:38:53 +0000364static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000365 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000366 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000367 &LocalAddrs,
368 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
369 &VLASizes,
370 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
371 const CapturedDecl *CD = FO.S->getCapturedDecl();
372 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 assert(CD->hasBody() && "missing CapturedDecl body");
374
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000375 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000377 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000378 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000379 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000380 Args.append(CD->param_begin(),
381 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000382 TargetArgs.append(
383 CD->param_begin(),
384 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000385 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000386 FunctionDecl *DebugFunctionDecl = nullptr;
387 if (!FO.UIntPtrCastRequired) {
388 FunctionProtoType::ExtProtoInfo EPI;
389 DebugFunctionDecl = FunctionDecl::Create(
390 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
391 SourceLocation(), DeclarationName(), Ctx.VoidTy,
392 Ctx.getTrivialTypeSourceInfo(
393 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
394 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
395 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000396 for (auto *FD : RD->fields()) {
397 QualType ArgType = FD->getType();
398 IdentifierInfo *II = nullptr;
399 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000400
401 // If this is a capture by copy and the type is not a pointer, the outlined
402 // function argument type should be uintptr and the value properly casted to
403 // uintptr. This is necessary given that the runtime library is only able to
404 // deal with pointers. We can pass in the same way the VLA type sizes to the
405 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000406 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 if (FO.UIntPtrCastRequired)
409 ArgType = Ctx.getUIntPtrType();
410 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000411
412 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000413 CapVar = I->getCapturedVar();
414 II = CapVar->getIdentifier();
415 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000416 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000417 else {
418 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000419 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000420 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000421 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000422 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000423 VarDecl *Arg;
424 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
425 Arg = ParmVarDecl::Create(
426 Ctx, DebugFunctionDecl,
427 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
428 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
429 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
430 } else {
431 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
432 II, ArgType, ImplicitParamDecl::Other);
433 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000434 Args.emplace_back(Arg);
435 // Do not cast arguments if we emit function with non-original types.
436 TargetArgs.emplace_back(
437 FO.UIntPtrCastRequired
438 ? Arg
439 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000440 ++I;
441 }
442 Args.append(
443 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
444 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000445 TargetArgs.append(
446 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
447 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000448
449 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000451 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000452 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
453
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000454 llvm::Function *F =
455 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
456 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000457 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
458 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000459 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000460
461 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000462 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
463 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000464 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000465 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000466 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000467 // Do not map arguments if we emit function with non-original types.
468 Address LocalAddr(Address::invalid());
469 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
470 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
471 TargetArgs[Cnt]);
472 } else {
473 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
474 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000475 // If we are capturing a pointer by copy we don't need to do anything, just
476 // use the value that we get from the arguments.
477 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000478 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000479 // If the variable is a reference we need to materialize it here.
480 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000481 Address RefAddr = CGF.CreateMemTemp(
482 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
483 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
484 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000485 LocalAddr = RefAddr;
486 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000487 if (!FO.RegisterCastedArgsOnly)
488 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000489 ++Cnt;
490 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000491 continue;
492 }
493
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000494 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
495 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000496 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000497 if (FO.UIntPtrCastRequired) {
498 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
499 Args[Cnt]->getName(),
500 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000501 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000502 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000503 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000506 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 } else if (I->capturesVariable()) {
508 auto *Var = I->getCapturedVar();
509 QualType VarTy = Var->getType();
510 Address ArgAddr = ArgLVal.getAddress();
511 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000512 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000513 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000514 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000517 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
518 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520 if (!FO.RegisterCastedArgsOnly) {
521 LocalAddrs.insert(
522 {Args[Cnt],
523 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
524 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000525 } else if (I->capturesVariableByCopy()) {
526 assert(!FD->getType()->isAnyPointerType() &&
527 "Not expecting a captured pointer.");
528 auto *Var = I->getCapturedVar();
529 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 LocalAddrs.insert(
531 {Args[Cnt],
532 {Var,
533 FO.UIntPtrCastRequired
534 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
535 ArgLVal, VarTy->isReferenceType())
536 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000537 } else {
538 // If 'this' is captured, load it into CXXThisValue.
539 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000540 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
541 .getScalarVal();
542 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000544 ++Cnt;
545 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000546 }
547
Alexey Bataeve754b182017-08-09 19:38:53 +0000548 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000549}
550
551llvm::Function *
552CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
553 assert(
554 CapturedStmtInfo &&
555 "CapturedStmtInfo should be set when generating the captured function");
556 const CapturedDecl *CD = S.getCapturedDecl();
557 // Build the argument list.
558 bool NeedWrapperFunction =
559 getDebugInfo() &&
560 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
561 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000562 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000563 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000564 SmallString<256> Buffer;
565 llvm::raw_svector_ostream Out(Buffer);
566 Out << CapturedStmtInfo->getHelperName();
567 if (NeedWrapperFunction)
568 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000569 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000570 Out.str());
571 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
572 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000573 for (const auto &LocalAddrPair : LocalAddrs) {
574 if (LocalAddrPair.second.first) {
575 setAddrOfLocalVar(LocalAddrPair.second.first,
576 LocalAddrPair.second.second);
577 }
578 }
579 for (const auto &VLASizePair : VLASizes)
580 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000581 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000582 CapturedStmtInfo->EmitBody(*this, CD->getBody());
583 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000584 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000585 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000586
Alexey Bataevefd884d2017-08-04 21:26:25 +0000587 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000588 /*RegisterCastedArgsOnly=*/true,
589 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000591 Args.clear();
592 LocalAddrs.clear();
593 VLASizes.clear();
594 llvm::Function *WrapperF =
595 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000596 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000597 llvm::SmallVector<llvm::Value *, 4> CallArgs;
598 for (const auto *Arg : Args) {
599 llvm::Value *CallArg;
600 auto I = LocalAddrs.find(Arg);
601 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000602 LValue LV = WrapperCGF.MakeAddrLValue(
603 I->second.second,
604 I->second.first ? I->second.first->getType() : Arg->getType(),
605 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
607 } else {
608 auto EI = VLASizes.find(Arg);
609 if (EI != VLASizes.end())
610 CallArg = EI->second.second;
611 else {
612 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000613 Arg->getType(),
614 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000615 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
616 }
617 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000618 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000619 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
621 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000622 WrapperCGF.FinishFunction();
623 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000624}
625
Alexey Bataev9959db52014-05-06 10:08:46 +0000626//===----------------------------------------------------------------------===//
627// OpenMP Directive Emission
628//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address DestAddr, Address SrcAddr, QualType OriginalType,
631 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000632 // Perform element-by-element initialization.
633 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000634
635 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000636 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000637 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
638 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
639
640 auto SrcBegin = SrcAddr.getPointer();
641 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
644 // The basic structure here is a while-do loop.
645 auto BodyBB = createBasicBlock("omp.arraycpy.body");
646 auto DoneBB = createBasicBlock("omp.arraycpy.done");
647 auto IsEmpty =
648 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
649 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000650
Alexey Bataev420d45b2015-04-14 05:11:24 +0000651 // Enter the loop body, making that address the current address.
652 auto EntryBB = Builder.GetInsertBlock();
653 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000654
655 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
656
657 llvm::PHINode *SrcElementPHI =
658 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
659 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
660 Address SrcElementCurrent =
661 Address(SrcElementPHI,
662 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
663
664 llvm::PHINode *DestElementPHI =
665 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
666 DestElementPHI->addIncoming(DestBegin, EntryBB);
667 Address DestElementCurrent =
668 Address(DestElementPHI,
669 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000670
Alexey Bataev420d45b2015-04-14 05:11:24 +0000671 // Emit copy.
672 CopyGen(DestElementCurrent, SrcElementCurrent);
673
674 // Shift the address forward by one element.
675 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000676 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000677 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000678 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000679 // Check whether we've reached the end.
680 auto Done =
681 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
682 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000683 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
684 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000685
686 // Done.
687 EmitBlock(DoneBB, /*IsFinished=*/true);
688}
689
John McCall7f416cc2015-09-08 08:05:57 +0000690void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
691 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000692 const VarDecl *SrcVD, const Expr *Copy) {
693 if (OriginalType->isArrayType()) {
694 auto *BO = dyn_cast<BinaryOperator>(Copy);
695 if (BO && BO->getOpcode() == BO_Assign) {
696 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000697 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000698 } else {
699 // For arrays with complex element types perform element by element
700 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000701 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000703 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000704 // Working with the single array element, so have to remap
705 // destination and source variables to corresponding array
706 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000707 CodeGenFunction::OMPPrivateScope Remap(*this);
708 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000709 return DestElement;
710 });
711 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000712 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000713 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000714 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000715 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000716 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000717 } else {
718 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000719 CodeGenFunction::OMPPrivateScope Remap(*this);
720 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
721 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 (void)Remap.Privatize();
723 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000724 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726}
727
Alexey Bataev69c62a92015-04-15 04:52:20 +0000728bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
729 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000730 if (!HaveInsertPoint())
731 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000732 bool FirstprivateIsLastprivate = false;
733 llvm::DenseSet<const VarDecl *> Lastprivates;
734 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
735 for (const auto *D : C->varlists())
736 Lastprivates.insert(
737 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
738 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000739 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000740 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
741 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
742 // Force emission of the firstprivate copy if the directive does not emit
743 // outlined function, like omp for, omp simd, omp distribute etc.
744 bool MustEmitFirstprivateCopy =
745 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000746 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000747 auto IRef = C->varlist_begin();
748 auto InitsRef = C->inits().begin();
749 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000750 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000751 bool ThisFirstprivateIsLastprivate =
752 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
753 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000754 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000755 !FD->getType()->isReferenceType()) {
756 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
757 ++IRef;
758 ++InitsRef;
759 continue;
760 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000761 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000762 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000763 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000764 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
765 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
766 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
768 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
769 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000770 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000771 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000772 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000773 // Emit VarDecl with copy init for arrays.
774 // Get the address of the original variable captured in current
775 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000776 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000777 auto Emission = EmitAutoVarAlloca(*VD);
778 auto *Init = VD->getInit();
779 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
780 // Perform simple memcpy.
781 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000782 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000783 } else {
784 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000785 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000786 [this, VDInit, Init](Address DestElement,
787 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000788 // Clean up any temporaries needed by the initialization.
789 RunCleanupsScope InitScope(*this);
790 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000791 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000792 EmitAnyExprToMem(Init, DestElement,
793 Init->getType().getQualifiers(),
794 /*IsInitializer*/ false);
795 LocalDeclMap.erase(VDInit);
796 });
797 }
798 EmitAutoVarCleanups(Emission);
799 return Emission.getAllocatedAddress();
800 });
801 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000802 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000803 // Emit private VarDecl with copy init.
804 // Remap temp VDInit variable to the address of the original
805 // variable
806 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000807 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000808 EmitDecl(*VD);
809 LocalDeclMap.erase(VDInit);
810 return GetAddrOfLocalVar(VD);
811 });
812 }
813 assert(IsRegistered &&
814 "firstprivate var already registered as private");
815 // Silence the warning about unused variable.
816 (void)IsRegistered;
817 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000818 ++IRef;
819 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000820 }
821 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000822 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000823}
824
Alexey Bataev03b340a2014-10-21 03:16:40 +0000825void CodeGenFunction::EmitOMPPrivateClause(
826 const OMPExecutableDirective &D,
827 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000828 if (!HaveInsertPoint())
829 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000830 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000831 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000832 auto IRef = C->varlist_begin();
833 for (auto IInit : C->private_copies()) {
834 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000835 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
836 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
837 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000838 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000839 // Emit private VarDecl with copy init.
840 EmitDecl(*VD);
841 return GetAddrOfLocalVar(VD);
842 });
843 assert(IsRegistered && "private var already registered as private");
844 // Silence the warning about unused variable.
845 (void)IsRegistered;
846 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000847 ++IRef;
848 }
849 }
850}
851
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000852bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000853 if (!HaveInsertPoint())
854 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855 // threadprivate_var1 = master_threadprivate_var1;
856 // operator=(threadprivate_var2, master_threadprivate_var2);
857 // ...
858 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000859 llvm::DenseSet<const VarDecl *> CopiedVars;
860 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000861 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000862 auto IRef = C->varlist_begin();
863 auto ISrcRef = C->source_exprs().begin();
864 auto IDestRef = C->destination_exprs().begin();
865 for (auto *AssignOp : C->assignment_ops()) {
866 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000867 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000868 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000869 // Get the address of the master variable. If we are emitting code with
870 // TLS support, the address is passed from the master as field in the
871 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000872 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000873 if (getLangOpts().OpenMPUseTLS &&
874 getContext().getTargetInfo().isTLSSupported()) {
875 assert(CapturedStmtInfo->lookup(VD) &&
876 "Copyin threadprivates should have been captured!");
877 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
878 VK_LValue, (*IRef)->getExprLoc());
879 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000880 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000881 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000882 MasterAddr =
883 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
884 : CGM.GetAddrOfGlobal(VD),
885 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000886 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000887 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000888 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000889 if (CopiedVars.size() == 1) {
890 // At first check if current thread is a master thread. If it is, no
891 // need to copy data.
892 CopyBegin = createBasicBlock("copyin.not.master");
893 CopyEnd = createBasicBlock("copyin.not.master.end");
894 Builder.CreateCondBr(
895 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000896 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
897 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000898 CopyBegin, CopyEnd);
899 EmitBlock(CopyBegin);
900 }
901 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
902 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000903 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000904 }
905 ++IRef;
906 ++ISrcRef;
907 ++IDestRef;
908 }
909 }
910 if (CopyEnd) {
911 // Exit out of copying procedure for non-master thread.
912 EmitBlock(CopyEnd, /*IsFinished=*/true);
913 return true;
914 }
915 return false;
916}
917
Alexey Bataev38e89532015-04-16 04:54:05 +0000918bool CodeGenFunction::EmitOMPLastprivateClauseInit(
919 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000920 if (!HaveInsertPoint())
921 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000922 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000923 llvm::DenseSet<const VarDecl *> SIMDLCVs;
924 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
925 auto *LoopDirective = cast<OMPLoopDirective>(&D);
926 for (auto *C : LoopDirective->counters()) {
927 SIMDLCVs.insert(
928 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
929 }
930 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000931 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000932 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000933 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000934 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
935 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000936 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 auto IRef = C->varlist_begin();
938 auto IDestRef = C->destination_exprs().begin();
939 for (auto *IInit : C->private_copies()) {
940 // Keep the address of the original variable for future update at the end
941 // of the loop.
942 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000943 // Taskloops do not require additional initialization, it is done in
944 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000945 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
946 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000947 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000948 DeclRefExpr DRE(
949 const_cast<VarDecl *>(OrigVD),
950 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
951 OrigVD) != nullptr,
952 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
953 return EmitLValue(&DRE).getAddress();
954 });
955 // Check if the variable is also a firstprivate: in this case IInit is
956 // not generated. Initialization of this variable will happen in codegen
957 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000958 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000959 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000960 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
961 // Emit private VarDecl with copy init.
962 EmitDecl(*VD);
963 return GetAddrOfLocalVar(VD);
964 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000965 assert(IsRegistered &&
966 "lastprivate var already registered as private");
967 (void)IsRegistered;
968 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000969 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000970 ++IRef;
971 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000972 }
973 }
974 return HasAtLeastOneLastprivate;
975}
976
977void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000978 const OMPExecutableDirective &D, bool NoFinals,
979 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000980 if (!HaveInsertPoint())
981 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000982 // Emit following code:
983 // if (<IsLastIterCond>) {
984 // orig_var1 = private_orig_var1;
985 // ...
986 // orig_varn = private_orig_varn;
987 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000988 llvm::BasicBlock *ThenBB = nullptr;
989 llvm::BasicBlock *DoneBB = nullptr;
990 if (IsLastIterCond) {
991 ThenBB = createBasicBlock(".omp.lastprivate.then");
992 DoneBB = createBasicBlock(".omp.lastprivate.done");
993 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
994 EmitBlock(ThenBB);
995 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000996 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
997 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000998 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000999 auto IC = LoopDirective->counters().begin();
1000 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001001 auto *D =
1002 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1003 if (NoFinals)
1004 AlreadyEmittedVars.insert(D);
1005 else
1006 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001007 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001008 }
1009 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001010 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1011 auto IRef = C->varlist_begin();
1012 auto ISrcRef = C->source_exprs().begin();
1013 auto IDestRef = C->destination_exprs().begin();
1014 for (auto *AssignOp : C->assignment_ops()) {
1015 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1016 QualType Type = PrivateVD->getType();
1017 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1018 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1019 // If lastprivate variable is a loop control variable for loop-based
1020 // directive, update its value before copyin back to original
1021 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001022 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1023 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001024 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1025 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1026 // Get the address of the original variable.
1027 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1028 // Get the address of the private variable.
1029 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1030 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1031 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001032 Address(Builder.CreateLoad(PrivateAddr),
1033 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001034 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001035 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001036 ++IRef;
1037 ++ISrcRef;
1038 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001040 if (auto *PostUpdate = C->getPostUpdateExpr())
1041 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001042 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001043 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001044 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001045}
1046
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001047void CodeGenFunction::EmitOMPReductionClauseInit(
1048 const OMPExecutableDirective &D,
1049 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001050 if (!HaveInsertPoint())
1051 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001052 SmallVector<const Expr *, 4> Shareds;
1053 SmallVector<const Expr *, 4> Privates;
1054 SmallVector<const Expr *, 4> ReductionOps;
1055 SmallVector<const Expr *, 4> LHSs;
1056 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001057 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001058 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001059 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001060 auto ILHS = C->lhs_exprs().begin();
1061 auto IRHS = C->rhs_exprs().begin();
1062 for (const auto *Ref : C->varlists()) {
1063 Shareds.emplace_back(Ref);
1064 Privates.emplace_back(*IPriv);
1065 ReductionOps.emplace_back(*IRed);
1066 LHSs.emplace_back(*ILHS);
1067 RHSs.emplace_back(*IRHS);
1068 std::advance(IPriv, 1);
1069 std::advance(IRed, 1);
1070 std::advance(ILHS, 1);
1071 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001072 }
1073 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001074 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1075 unsigned Count = 0;
1076 auto ILHS = LHSs.begin();
1077 auto IRHS = RHSs.begin();
1078 auto IPriv = Privates.begin();
1079 for (const auto *IRef : Shareds) {
1080 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1081 // Emit private VarDecl with reduction init.
1082 RedCG.emitSharedLValue(*this, Count);
1083 RedCG.emitAggregateType(*this, Count);
1084 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1085 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1086 RedCG.getSharedLValue(Count),
1087 [&Emission](CodeGenFunction &CGF) {
1088 CGF.EmitAutoVarInit(Emission);
1089 return true;
1090 });
1091 EmitAutoVarCleanups(Emission);
1092 Address BaseAddr = RedCG.adjustPrivateAddress(
1093 *this, Count, Emission.getAllocatedAddress());
1094 bool IsRegistered = PrivateScope.addPrivate(
1095 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1096 assert(IsRegistered && "private var already registered as private");
1097 // Silence the warning about unused variable.
1098 (void)IsRegistered;
1099
1100 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1101 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001102 QualType Type = PrivateVD->getType();
1103 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1104 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001105 // Store the address of the original variable associated with the LHS
1106 // implicit variable.
1107 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1108 return RedCG.getSharedLValue(Count).getAddress();
1109 });
1110 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1111 return GetAddrOfLocalVar(PrivateVD);
1112 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001113 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1114 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001115 // Store the address of the original variable associated with the LHS
1116 // implicit variable.
1117 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1118 return RedCG.getSharedLValue(Count).getAddress();
1119 });
1120 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1121 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1122 ConvertTypeForMem(RHSVD->getType()),
1123 "rhs.begin");
1124 });
1125 } else {
1126 QualType Type = PrivateVD->getType();
1127 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1128 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1129 // Store the address of the original variable associated with the LHS
1130 // implicit variable.
1131 if (IsArray) {
1132 OriginalAddr = Builder.CreateElementBitCast(
1133 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1134 }
1135 PrivateScope.addPrivate(
1136 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1137 PrivateScope.addPrivate(
1138 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1139 return IsArray
1140 ? Builder.CreateElementBitCast(
1141 GetAddrOfLocalVar(PrivateVD),
1142 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1143 : GetAddrOfLocalVar(PrivateVD);
1144 });
1145 }
1146 ++ILHS;
1147 ++IRHS;
1148 ++IPriv;
1149 ++Count;
1150 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001151}
1152
1153void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001154 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001155 if (!HaveInsertPoint())
1156 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001157 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158 llvm::SmallVector<const Expr *, 8> LHSExprs;
1159 llvm::SmallVector<const Expr *, 8> RHSExprs;
1160 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001161 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001162 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001163 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001164 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1166 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1167 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1168 }
1169 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001170 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1171 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001172 ReductionKind == OMPD_simd;
1173 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001174 // Emit nowait reduction if nowait clause is present or directive is a
1175 // parallel directive (it always has implicit barrier).
1176 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001177 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001178 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001179 }
1180}
1181
Alexey Bataev61205072016-03-02 04:57:40 +00001182static void emitPostUpdateForReductionClause(
1183 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1184 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1185 if (!CGF.HaveInsertPoint())
1186 return;
1187 llvm::BasicBlock *DoneBB = nullptr;
1188 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1189 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1190 if (!DoneBB) {
1191 if (auto *Cond = CondGen(CGF)) {
1192 // If the first post-update expression is found, emit conditional
1193 // block if it was requested.
1194 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1195 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1196 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1197 CGF.EmitBlock(ThenBB);
1198 }
1199 }
1200 CGF.EmitIgnoredExpr(PostUpdate);
1201 }
1202 }
1203 if (DoneBB)
1204 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1205}
1206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001207namespace {
1208/// Codegen lambda for appending distribute lower and upper bounds to outlined
1209/// parallel function. This is necessary for combined constructs such as
1210/// 'distribute parallel for'
1211typedef llvm::function_ref<void(CodeGenFunction &,
1212 const OMPExecutableDirective &,
1213 llvm::SmallVectorImpl<llvm::Value *> &)>
1214 CodeGenBoundParametersTy;
1215} // anonymous namespace
1216
1217static void emitCommonOMPParallelDirective(
1218 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1219 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1220 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001221 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1222 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1223 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001224 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001225 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001226 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1227 /*IgnoreResultAssign*/ true);
1228 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1229 CGF, NumThreads, NumThreadsClause->getLocStart());
1230 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001231 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001232 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001233 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1234 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1235 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001236 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001237 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1238 if (C->getNameModifier() == OMPD_unknown ||
1239 C->getNameModifier() == OMPD_parallel) {
1240 IfCond = C->getCondition();
1241 break;
1242 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001243 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001244
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001245 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001246 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001247 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1248 // lower and upper bounds with the pragma 'for' chunking mechanism.
1249 // The following lambda takes care of appending the lower and upper bound
1250 // parameters when necessary
1251 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001252 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001253 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001254 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001255}
1256
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001257static void emitEmptyBoundParameters(CodeGenFunction &,
1258 const OMPExecutableDirective &,
1259 llvm::SmallVectorImpl<llvm::Value *> &) {}
1260
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001261void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001262 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001263 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001265 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001266 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1267 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001268 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001269 // propagation master's thread values of threadprivate variables to local
1270 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001271 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1272 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1273 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001274 }
1275 CGF.EmitOMPPrivateClause(S, PrivateScope);
1276 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1277 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001278 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001279 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001280 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001281 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1282 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001283 emitPostUpdateForReductionClause(
1284 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001285}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001286
Alexey Bataev0f34da12015-07-02 04:17:07 +00001287void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1288 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001289 RunCleanupsScope BodyScope(*this);
1290 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001291 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 EmitIgnoredExpr(I);
1293 }
Alexander Musman3276a272015-03-21 10:12:56 +00001294 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001295 // In distribute directives only loop counters may be marked as linear, no
1296 // need to generate the code for them.
1297 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1298 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1299 for (auto *U : C->updates())
1300 EmitIgnoredExpr(U);
1301 }
Alexander Musman3276a272015-03-21 10:12:56 +00001302 }
1303
Alexander Musmana5f070a2014-10-01 06:03:56 +00001304 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001305 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001306 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001307 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001308 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309 // The end (updates/cleanups).
1310 EmitBlock(Continue.getBlock());
1311 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001312}
1313
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314void CodeGenFunction::EmitOMPInnerLoop(
1315 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1316 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001317 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1318 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001319 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001320
1321 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001322 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001323 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001324 const SourceRange &R = S.getSourceRange();
1325 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1326 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001327
1328 // If there are any cleanups between here and the loop-exit scope,
1329 // create a block to stage a loop exit along.
1330 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001331 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001332 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001333
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
Alexey Bataev2df54a02015-03-12 08:53:29 +00001336 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001337 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338 if (ExitBlock != LoopExit.getBlock()) {
1339 EmitBlock(ExitBlock);
1340 EmitBranchThroughCleanup(LoopExit);
1341 }
1342
1343 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001344 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001345
1346 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001347 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1349
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001350 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001351
1352 // Emit "IV = IV + 1" and a back-edge to the condition block.
1353 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001354 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001355 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001356 BreakContinueStack.pop_back();
1357 EmitBranch(CondBlock);
1358 LoopStack.pop();
1359 // Emit the fall-through block.
1360 EmitBlock(LoopExit.getBlock());
1361}
1362
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001363bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001364 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001365 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001366 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001368 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001369 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001370 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001371 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001372 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1373 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1374 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1375 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1376 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1377 VD->getInit()->getType(), VK_LValue,
1378 VD->getInit()->getExprLoc());
1379 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1380 VD->getType()),
1381 /*capturedByInit=*/false);
1382 EmitAutoVarCleanups(Emission);
1383 } else
1384 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001385 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001386 // Emit the linear steps for the linear clauses.
1387 // If a step is not constant, it is pre-calculated before the loop.
1388 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1389 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001390 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001391 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001392 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001394 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001395 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001396}
1397
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398void CodeGenFunction::EmitOMPLinearClauseFinal(
1399 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001400 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001402 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001403 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001404 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001405 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001406 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001407 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001408 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001410 // If the first post-update expression is found, emit conditional
1411 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1413 DoneBB = createBasicBlock(".omp.linear.pu.done");
1414 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1415 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001416 }
1417 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1419 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001420 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001422 Address OrigAddr = EmitLValue(&DRE).getAddress();
1423 CodeGenFunction::OMPPrivateScope VarScope(*this);
1424 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001426 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001427 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001428 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001429 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001430 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001431 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001432 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001434}
1435
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001436static void emitAlignedClause(CodeGenFunction &CGF,
1437 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001438 if (!CGF.HaveInsertPoint())
1439 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001440 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001441 unsigned ClauseAlignment = 0;
1442 if (auto AlignmentExpr = Clause->getAlignment()) {
1443 auto AlignmentCI =
1444 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1445 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001446 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001447 for (auto E : Clause->varlists()) {
1448 unsigned Alignment = ClauseAlignment;
1449 if (Alignment == 0) {
1450 // OpenMP [2.8.1, Description]
1451 // If no optional parameter is specified, implementation-defined default
1452 // alignments for SIMD instructions on the target platforms are assumed.
1453 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001454 CGF.getContext()
1455 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1456 E->getType()->getPointeeType()))
1457 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001458 }
1459 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1460 "alignment is not power of 2");
1461 if (Alignment != 0) {
1462 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1463 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1464 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001465 }
1466 }
1467}
1468
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001469void CodeGenFunction::EmitOMPPrivateLoopCounters(
1470 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1471 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001472 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001473 auto I = S.private_counters().begin();
1474 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001475 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1476 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001477 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001478 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001479 if (!LocalDeclMap.count(PrivateVD)) {
1480 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1481 EmitAutoVarCleanups(VarEmission);
1482 }
1483 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1484 /*RefersToEnclosingVariableOrCapture=*/false,
1485 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1486 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001487 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001488 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1489 VD->hasGlobalStorage()) {
1490 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1491 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1492 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1493 E->getType(), VK_LValue, E->getExprLoc());
1494 return EmitLValue(&DRE).getAddress();
1495 });
1496 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001497 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001498 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001499}
1500
Alexey Bataev62dbb972015-04-22 11:59:37 +00001501static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1502 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1503 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001504 if (!CGF.HaveInsertPoint())
1505 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001506 {
1507 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001508 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001509 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001510 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001511 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 CGF.EmitIgnoredExpr(I);
1513 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001514 }
1515 // Check that loop is executed at least one time.
1516 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1517}
1518
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001519void CodeGenFunction::EmitOMPLinearClause(
1520 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1521 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001522 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001523 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1524 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1525 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1526 for (auto *C : LoopDirective->counters()) {
1527 SIMDLCVs.insert(
1528 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1529 }
1530 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001531 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001532 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001533 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001534 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1535 auto *PrivateVD =
1536 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001537 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1538 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1539 // Emit private VarDecl with copy init.
1540 EmitVarDecl(*PrivateVD);
1541 return GetAddrOfLocalVar(PrivateVD);
1542 });
1543 assert(IsRegistered && "linear var already registered as private");
1544 // Silence the warning about unused variable.
1545 (void)IsRegistered;
1546 } else
1547 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001548 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001549 }
1550 }
1551}
1552
Alexey Bataev45bfad52015-08-21 12:19:04 +00001553static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001554 const OMPExecutableDirective &D,
1555 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001556 if (!CGF.HaveInsertPoint())
1557 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001558 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001559 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1560 /*ignoreResult=*/true);
1561 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1562 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1563 // In presence of finite 'safelen', it may be unsafe to mark all
1564 // the memory instructions parallel, because loop-carried
1565 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001566 if (!IsMonotonic)
1567 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001568 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001569 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1570 /*ignoreResult=*/true);
1571 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001572 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001573 // In presence of finite 'safelen', it may be unsafe to mark all
1574 // the memory instructions parallel, because loop-carried
1575 // dependences of 'safelen' iterations are possible.
1576 CGF.LoopStack.setParallel(false);
1577 }
1578}
1579
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001580void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1581 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001582 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001583 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001584 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001585 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001586}
1587
Alexey Bataevef549a82016-03-09 09:49:09 +00001588void CodeGenFunction::EmitOMPSimdFinal(
1589 const OMPLoopDirective &D,
1590 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001591 if (!HaveInsertPoint())
1592 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001593 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001594 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001595 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001596 for (auto F : D.finals()) {
1597 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001598 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1599 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1600 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1601 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001602 if (!DoneBB) {
1603 if (auto *Cond = CondGen(*this)) {
1604 // If the first post-update expression is found, emit conditional
1605 // block if it was requested.
1606 auto *ThenBB = createBasicBlock(".omp.final.then");
1607 DoneBB = createBasicBlock(".omp.final.done");
1608 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1609 EmitBlock(ThenBB);
1610 }
1611 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001612 Address OrigAddr = Address::invalid();
1613 if (CED)
1614 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1615 else {
1616 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1617 /*RefersToEnclosingVariableOrCapture=*/false,
1618 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1619 OrigAddr = EmitLValue(&DRE).getAddress();
1620 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001621 OMPPrivateScope VarScope(*this);
1622 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001623 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001624 (void)VarScope.Privatize();
1625 EmitIgnoredExpr(F);
1626 }
1627 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001628 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001629 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001630 if (DoneBB)
1631 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632}
1633
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001634static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1635 const OMPLoopDirective &S,
1636 CodeGenFunction::JumpDest LoopExit) {
1637 CGF.EmitOMPLoopBody(S, LoopExit);
1638 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001639}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001640
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001641/// Emit a helper variable and return corresponding lvalue.
1642static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1643 const DeclRefExpr *Helper) {
1644 auto VDecl = cast<VarDecl>(Helper->getDecl());
1645 CGF.EmitVarDecl(*VDecl);
1646 return CGF.EmitLValue(Helper);
1647}
1648
Alexey Bataevf8365372017-11-17 17:57:25 +00001649static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1650 PrePostActionTy &Action) {
1651 Action.Enter(CGF);
1652 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1653 "Expected simd directive");
1654 OMPLoopScope PreInitScope(CGF, S);
1655 // if (PreCond) {
1656 // for (IV in 0..LastIteration) BODY;
1657 // <Final counter/linear vars updates>;
1658 // }
1659 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001660 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1661 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1662 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1663 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1664 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1665 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001666
Alexey Bataevf8365372017-11-17 17:57:25 +00001667 // Emit: if (PreCond) - begin.
1668 // If the condition constant folds and can be elided, avoid emitting the
1669 // whole loop.
1670 bool CondConstant;
1671 llvm::BasicBlock *ContBlock = nullptr;
1672 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1673 if (!CondConstant)
1674 return;
1675 } else {
1676 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1677 ContBlock = CGF.createBasicBlock("simd.if.end");
1678 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1679 CGF.getProfileCount(&S));
1680 CGF.EmitBlock(ThenBlock);
1681 CGF.incrementProfileCounter(&S);
1682 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001683
Alexey Bataevf8365372017-11-17 17:57:25 +00001684 // Emit the loop iteration variable.
1685 const Expr *IVExpr = S.getIterationVariable();
1686 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1687 CGF.EmitVarDecl(*IVDecl);
1688 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001689
Alexey Bataevf8365372017-11-17 17:57:25 +00001690 // Emit the iterations count variable.
1691 // If it is not a variable, Sema decided to calculate iterations count on
1692 // each iteration (e.g., it is foldable into a constant).
1693 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1694 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1695 // Emit calculation of the iterations count.
1696 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1697 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001698
Alexey Bataevf8365372017-11-17 17:57:25 +00001699 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001700
Alexey Bataevf8365372017-11-17 17:57:25 +00001701 emitAlignedClause(CGF, S);
1702 (void)CGF.EmitOMPLinearClauseInit(S);
1703 {
1704 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1705 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1706 CGF.EmitOMPLinearClause(S, LoopScope);
1707 CGF.EmitOMPPrivateClause(S, LoopScope);
1708 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1709 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1710 (void)LoopScope.Privatize();
1711 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1712 S.getInc(),
1713 [&S](CodeGenFunction &CGF) {
1714 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1715 CGF.EmitStopPoint(&S);
1716 },
1717 [](CodeGenFunction &) {});
1718 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001719 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001720 // Emit final copy of the lastprivate variables at the end of loops.
1721 if (HasLastprivateClause)
1722 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1723 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1724 emitPostUpdateForReductionClause(
1725 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1726 }
1727 CGF.EmitOMPLinearClauseFinal(
1728 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1729 // Emit: if (PreCond) - end.
1730 if (ContBlock) {
1731 CGF.EmitBranch(ContBlock);
1732 CGF.EmitBlock(ContBlock, true);
1733 }
1734}
1735
1736void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1737 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1738 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001739 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001740 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001741 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001742}
1743
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001744void CodeGenFunction::EmitOMPOuterLoop(
1745 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1746 CodeGenFunction::OMPPrivateScope &LoopScope,
1747 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1748 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1749 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001750 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001751
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752 const Expr *IVExpr = S.getIterationVariable();
1753 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1754 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1755
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001756 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1757
1758 // Start the loop with a block that tests the condition.
1759 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1760 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001761 const SourceRange &R = S.getSourceRange();
1762 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1763 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001764
1765 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001766 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001767 // UB = min(UB, GlobalUB) or
1768 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1769 // 'distribute parallel for')
1770 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001771 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001772 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001773 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001774 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001775 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001776 BoolCondVal =
1777 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1778 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001779 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001780
1781 // If there are any cleanups between here and the loop-exit scope,
1782 // create a block to stage a loop exit along.
1783 auto ExitBlock = LoopExit.getBlock();
1784 if (LoopScope.requiresCleanups())
1785 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1786
1787 auto LoopBody = createBasicBlock("omp.dispatch.body");
1788 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1789 if (ExitBlock != LoopExit.getBlock()) {
1790 EmitBlock(ExitBlock);
1791 EmitBranchThroughCleanup(LoopExit);
1792 }
1793 EmitBlock(LoopBody);
1794
Alexander Musman92bdaab2015-03-12 13:37:50 +00001795 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1796 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001797 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001798 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001799
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001800 // Create a block for the increment.
1801 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1802 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1803
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001804 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1805 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001806 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1807 LoopStack.setParallel(!IsMonotonic);
1808 else
1809 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001810
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001811 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001812
1813 // when 'distribute' is not combined with a 'for':
1814 // while (idx <= UB) { BODY; ++idx; }
1815 // when 'distribute' is combined with a 'for'
1816 // (e.g. 'distribute parallel for')
1817 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1818 EmitOMPInnerLoop(
1819 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1820 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1821 CodeGenLoop(CGF, S, LoopExit);
1822 },
1823 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1824 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1825 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001826
1827 EmitBlock(Continue.getBlock());
1828 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001829 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001830 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001831 EmitIgnoredExpr(LoopArgs.NextLB);
1832 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001833 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001834
1835 EmitBranch(CondBlock);
1836 LoopStack.pop();
1837 // Emit the fall-through block.
1838 EmitBlock(LoopExit.getBlock());
1839
1840 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001841 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1842 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001843 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1844 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001845 };
1846 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001847}
1848
1849void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001850 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001851 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001852 const OMPLoopArguments &LoopArgs,
1853 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001854 auto &RT = CGM.getOpenMPRuntime();
1855
1856 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001857 const bool DynamicOrOrdered =
1858 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001859
1860 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001861 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001862 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001863 "static non-chunked schedule does not need outer loop");
1864
1865 // Emit outer loop.
1866 //
1867 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1868 // When schedule(dynamic,chunk_size) is specified, the iterations are
1869 // distributed to threads in the team in chunks as the threads request them.
1870 // Each thread executes a chunk of iterations, then requests another chunk,
1871 // until no chunks remain to be distributed. Each chunk contains chunk_size
1872 // iterations, except for the last chunk to be distributed, which may have
1873 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1874 //
1875 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1876 // to threads in the team in chunks as the executing threads request them.
1877 // Each thread executes a chunk of iterations, then requests another chunk,
1878 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1879 // each chunk is proportional to the number of unassigned iterations divided
1880 // by the number of threads in the team, decreasing to 1. For a chunk_size
1881 // with value k (greater than 1), the size of each chunk is determined in the
1882 // same way, with the restriction that the chunks do not contain fewer than k
1883 // iterations (except for the last chunk to be assigned, which may have fewer
1884 // than k iterations).
1885 //
1886 // When schedule(auto) is specified, the decision regarding scheduling is
1887 // delegated to the compiler and/or runtime system. The programmer gives the
1888 // implementation the freedom to choose any possible mapping of iterations to
1889 // threads in the team.
1890 //
1891 // When schedule(runtime) is specified, the decision regarding scheduling is
1892 // deferred until run time, and the schedule and chunk size are taken from the
1893 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1894 // implementation defined
1895 //
1896 // while(__kmpc_dispatch_next(&LB, &UB)) {
1897 // idx = LB;
1898 // while (idx <= UB) { BODY; ++idx;
1899 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1900 // } // inner loop
1901 // }
1902 //
1903 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1904 // When schedule(static, chunk_size) is specified, iterations are divided into
1905 // chunks of size chunk_size, and the chunks are assigned to the threads in
1906 // the team in a round-robin fashion in the order of the thread number.
1907 //
1908 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1909 // while (idx <= UB) { BODY; ++idx; } // inner loop
1910 // LB = LB + ST;
1911 // UB = UB + ST;
1912 // }
1913 //
1914
1915 const Expr *IVExpr = S.getIterationVariable();
1916 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1917 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1918
1919 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001920 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1921 llvm::Value *LBVal = DispatchBounds.first;
1922 llvm::Value *UBVal = DispatchBounds.second;
1923 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1924 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001925 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001926 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001927 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001928 CGOpenMPRuntime::StaticRTInput StaticInit(
1929 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1930 LoopArgs.ST, LoopArgs.Chunk);
1931 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1932 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001933 }
1934
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001935 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1936 const unsigned IVSize,
1937 const bool IVSigned) {
1938 if (Ordered) {
1939 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1940 IVSigned);
1941 }
1942 };
1943
1944 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1945 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1946 OuterLoopArgs.IncExpr = S.getInc();
1947 OuterLoopArgs.Init = S.getInit();
1948 OuterLoopArgs.Cond = S.getCond();
1949 OuterLoopArgs.NextLB = S.getNextLowerBound();
1950 OuterLoopArgs.NextUB = S.getNextUpperBound();
1951 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1952 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001953}
1954
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001955static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1956 const unsigned IVSize, const bool IVSigned) {}
1957
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001958void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001959 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1960 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1961 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001962
1963 auto &RT = CGM.getOpenMPRuntime();
1964
1965 // Emit outer loop.
1966 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1967 // dynamic
1968 //
1969
1970 const Expr *IVExpr = S.getIterationVariable();
1971 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1972 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1973
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001974 CGOpenMPRuntime::StaticRTInput StaticInit(
1975 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1976 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1977 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001978
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001979 // for combined 'distribute' and 'for' the increment expression of distribute
1980 // is store in DistInc. For 'distribute' alone, it is in Inc.
1981 Expr *IncExpr;
1982 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1983 IncExpr = S.getDistInc();
1984 else
1985 IncExpr = S.getInc();
1986
1987 // this routine is shared by 'omp distribute parallel for' and
1988 // 'omp distribute': select the right EUB expression depending on the
1989 // directive
1990 OMPLoopArguments OuterLoopArgs;
1991 OuterLoopArgs.LB = LoopArgs.LB;
1992 OuterLoopArgs.UB = LoopArgs.UB;
1993 OuterLoopArgs.ST = LoopArgs.ST;
1994 OuterLoopArgs.IL = LoopArgs.IL;
1995 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1996 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1997 ? S.getCombinedEnsureUpperBound()
1998 : S.getEnsureUpperBound();
1999 OuterLoopArgs.IncExpr = IncExpr;
2000 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2001 ? S.getCombinedInit()
2002 : S.getInit();
2003 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2004 ? S.getCombinedCond()
2005 : S.getCond();
2006 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2007 ? S.getCombinedNextLowerBound()
2008 : S.getNextLowerBound();
2009 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2010 ? S.getCombinedNextUpperBound()
2011 : S.getNextUpperBound();
2012
2013 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2014 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2015 emitEmptyOrdered);
2016}
2017
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002018static std::pair<LValue, LValue>
2019emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2020 const OMPExecutableDirective &S) {
2021 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2022 LValue LB =
2023 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2024 LValue UB =
2025 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2026
2027 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2028 // parallel for') we need to use the 'distribute'
2029 // chunk lower and upper bounds rather than the whole loop iteration
2030 // space. These are parameters to the outlined function for 'parallel'
2031 // and we copy the bounds of the previous schedule into the
2032 // the current ones.
2033 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2034 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2035 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
2036 PrevLBVal = CGF.EmitScalarConversion(
2037 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2038 LS.getIterationVariable()->getType(), SourceLocation());
2039 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
2040 PrevUBVal = CGF.EmitScalarConversion(
2041 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2042 LS.getIterationVariable()->getType(), SourceLocation());
2043
2044 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2045 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2046
2047 return {LB, UB};
2048}
2049
2050/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2051/// we need to use the LB and UB expressions generated by the worksharing
2052/// code generation support, whereas in non combined situations we would
2053/// just emit 0 and the LastIteration expression
2054/// This function is necessary due to the difference of the LB and UB
2055/// types for the RT emission routines for 'for_static_init' and
2056/// 'for_dispatch_init'
2057static std::pair<llvm::Value *, llvm::Value *>
2058emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2059 const OMPExecutableDirective &S,
2060 Address LB, Address UB) {
2061 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2062 const Expr *IVExpr = LS.getIterationVariable();
2063 // when implementing a dynamic schedule for a 'for' combined with a
2064 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2065 // is not normalized as each team only executes its own assigned
2066 // distribute chunk
2067 QualType IteratorTy = IVExpr->getType();
2068 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
2069 SourceLocation());
2070 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
2071 SourceLocation());
2072 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002073}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002074
2075static void emitDistributeParallelForDistributeInnerBoundParams(
2076 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2077 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2078 const auto &Dir = cast<OMPLoopDirective>(S);
2079 LValue LB =
2080 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2081 auto LBCast = CGF.Builder.CreateIntCast(
2082 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2083 CapturedVars.push_back(LBCast);
2084 LValue UB =
2085 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2086
2087 auto UBCast = CGF.Builder.CreateIntCast(
2088 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2089 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002090}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002091
2092static void
2093emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2094 const OMPLoopDirective &S,
2095 CodeGenFunction::JumpDest LoopExit) {
2096 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2097 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002098 bool HasCancel = false;
2099 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2100 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2101 HasCancel = D->hasCancel();
2102 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2103 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002104 else if (const auto *D =
2105 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2106 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002107 }
2108 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2109 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002110 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2111 emitDistributeParallelForInnerBounds,
2112 emitDistributeParallelForDispatchBounds);
2113 };
2114
2115 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002116 CGF, S,
2117 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2118 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002119 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002120}
2121
Carlo Bertolli9925f152016-06-27 14:55:37 +00002122void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2123 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2125 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2126 S.getDistInc());
2127 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002128 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002129 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002130}
2131
Kelvin Li4a39add2016-07-05 05:00:15 +00002132void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2133 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002134 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2135 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2136 S.getDistInc());
2137 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002138 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002139 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002140}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002141
2142void CodeGenFunction::EmitOMPDistributeSimdDirective(
2143 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002144 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2145 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2146 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002147 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002148 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002149}
2150
Alexey Bataevf8365372017-11-17 17:57:25 +00002151void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2152 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2153 // Emit SPMD target parallel for region as a standalone region.
2154 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2155 emitOMPSimdRegion(CGF, S, Action);
2156 };
2157 llvm::Function *Fn;
2158 llvm::Constant *Addr;
2159 // Emit target region as a standalone region.
2160 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2161 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2162 assert(Fn && Addr && "Target device function emission failed.");
2163}
2164
Kelvin Li986330c2016-07-20 22:57:10 +00002165void CodeGenFunction::EmitOMPTargetSimdDirective(
2166 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002167 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2168 emitOMPSimdRegion(CGF, S, Action);
2169 };
2170 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002171}
2172
Kelvin Li1851df52017-01-03 05:23:48 +00002173void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2174 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002175 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Kelvin Li1851df52017-01-03 05:23:48 +00002176 CGM.getOpenMPRuntime().emitInlinedDirective(
2177 *this, OMPD_target_teams_distribute_parallel_for_simd,
2178 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002179 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Kelvin Li1851df52017-01-03 05:23:48 +00002180 });
2181}
2182
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002183namespace {
2184 struct ScheduleKindModifiersTy {
2185 OpenMPScheduleClauseKind Kind;
2186 OpenMPScheduleClauseModifier M1;
2187 OpenMPScheduleClauseModifier M2;
2188 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2189 OpenMPScheduleClauseModifier M1,
2190 OpenMPScheduleClauseModifier M2)
2191 : Kind(Kind), M1(M1), M2(M2) {}
2192 };
2193} // namespace
2194
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002195bool CodeGenFunction::EmitOMPWorksharingLoop(
2196 const OMPLoopDirective &S, Expr *EUB,
2197 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2198 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002199 // Emit the loop iteration variable.
2200 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2201 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2202 EmitVarDecl(*IVDecl);
2203
2204 // Emit the iterations count variable.
2205 // If it is not a variable, Sema decided to calculate iterations count on each
2206 // iteration (e.g., it is foldable into a constant).
2207 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2208 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2209 // Emit calculation of the iterations count.
2210 EmitIgnoredExpr(S.getCalcLastIteration());
2211 }
2212
2213 auto &RT = CGM.getOpenMPRuntime();
2214
Alexey Bataev38e89532015-04-16 04:54:05 +00002215 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002216 // Check pre-condition.
2217 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002218 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002219 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002220 // If the condition constant folds and can be elided, avoid emitting the
2221 // whole loop.
2222 bool CondConstant;
2223 llvm::BasicBlock *ContBlock = nullptr;
2224 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2225 if (!CondConstant)
2226 return false;
2227 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002228 auto *ThenBlock = createBasicBlock("omp.precond.then");
2229 ContBlock = createBasicBlock("omp.precond.end");
2230 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002231 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002232 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002233 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002234 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002235
Alexey Bataev8b427062016-05-25 12:36:08 +00002236 bool Ordered = false;
2237 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2238 if (OrderedClause->getNumForLoops())
2239 RT.emitDoacrossInit(*this, S);
2240 else
2241 Ordered = true;
2242 }
2243
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002244 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002245 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002246 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002247 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002248
2249 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2250 LValue LB = Bounds.first;
2251 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002252 LValue ST =
2253 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2254 LValue IL =
2255 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2256
Alexander Musmanc6388682014-12-15 07:07:06 +00002257 // Emit 'then' code.
2258 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002259 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002260 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002261 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002262 // initialization of firstprivate variables and post-update of
2263 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002264 CGM.getOpenMPRuntime().emitBarrierCall(
2265 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2266 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002267 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002268 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002269 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002270 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002271 EmitOMPPrivateLoopCounters(S, LoopScope);
2272 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002273 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002274
2275 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002276 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002277 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002278 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002279 ScheduleKind.Schedule = C->getScheduleKind();
2280 ScheduleKind.M1 = C->getFirstScheduleModifier();
2281 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002282 if (const auto *Ch = C->getChunkSize()) {
2283 Chunk = EmitScalarExpr(Ch);
2284 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2285 S.getIterationVariable()->getType(),
2286 S.getLocStart());
2287 }
2288 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002289 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2290 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002291 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2292 // If the static schedule kind is specified or if the ordered clause is
2293 // specified, and if no monotonic modifier is specified, the effect will
2294 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002295 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002296 /* Chunked */ Chunk != nullptr) &&
2297 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002298 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2299 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002300 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2301 // When no chunk_size is specified, the iteration space is divided into
2302 // chunks that are approximately equal in size, and at most one chunk is
2303 // distributed to each thread. Note that the size of the chunks is
2304 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002305 CGOpenMPRuntime::StaticRTInput StaticInit(
2306 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2307 UB.getAddress(), ST.getAddress());
2308 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2309 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002310 auto LoopExit =
2311 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002312 // UB = min(UB, GlobalUB);
2313 EmitIgnoredExpr(S.getEnsureUpperBound());
2314 // IV = LB;
2315 EmitIgnoredExpr(S.getInit());
2316 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002317 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2318 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002319 [&S, LoopExit](CodeGenFunction &CGF) {
2320 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002321 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002322 },
2323 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002324 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002325 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002326 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002327 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2328 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002329 };
2330 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002331 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002332 const bool IsMonotonic =
2333 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2334 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2335 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2336 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002337 // Emit the outer loop, which requests its work chunk [LB..UB] from
2338 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002339 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2340 ST.getAddress(), IL.getAddress(),
2341 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002342 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002343 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002344 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002345 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2346 EmitOMPSimdFinal(S,
2347 [&](CodeGenFunction &CGF) -> llvm::Value * {
2348 return CGF.Builder.CreateIsNotNull(
2349 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2350 });
2351 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002352 EmitOMPReductionClauseFinal(
2353 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2354 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2355 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002356 // Emit post-update of the reduction variables if IsLastIter != 0.
2357 emitPostUpdateForReductionClause(
2358 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2359 return CGF.Builder.CreateIsNotNull(
2360 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2361 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002362 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2363 if (HasLastprivateClause)
2364 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002365 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2366 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002367 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002368 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002369 return CGF.Builder.CreateIsNotNull(
2370 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2371 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002372 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002373 if (ContBlock) {
2374 EmitBranch(ContBlock);
2375 EmitBlock(ContBlock, true);
2376 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002377 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002378 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002379}
2380
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002381/// The following two functions generate expressions for the loop lower
2382/// and upper bounds in case of static and dynamic (dispatch) schedule
2383/// of the associated 'for' or 'distribute' loop.
2384static std::pair<LValue, LValue>
2385emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2386 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2387 LValue LB =
2388 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2389 LValue UB =
2390 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2391 return {LB, UB};
2392}
2393
2394/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2395/// consider the lower and upper bound expressions generated by the
2396/// worksharing loop support, but we use 0 and the iteration space size as
2397/// constants
2398static std::pair<llvm::Value *, llvm::Value *>
2399emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2400 Address LB, Address UB) {
2401 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2402 const Expr *IVExpr = LS.getIterationVariable();
2403 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2404 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2405 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2406 return {LBVal, UBVal};
2407}
2408
Alexander Musmanc6388682014-12-15 07:07:06 +00002409void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002410 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002411 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2412 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002413 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002414 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2415 emitForLoopBounds,
2416 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002417 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002418 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002419 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002420 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2421 S.hasCancel());
2422 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002423
2424 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002425 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002426 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2427 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002428}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002429
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002430void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002431 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002432 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2433 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002434 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2435 emitForLoopBounds,
2436 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002437 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002438 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002439 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002440 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2441 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002442
2443 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002444 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002445 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2446 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002447}
2448
Alexey Bataev2df54a02015-03-12 08:53:29 +00002449static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2450 const Twine &Name,
2451 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002452 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002453 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002454 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002455 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002456}
2457
Alexey Bataev3392d762016-02-16 11:18:12 +00002458void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002459 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2460 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002461 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002462 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2463 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002464 auto &C = CGF.CGM.getContext();
2465 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2466 // Emit helper vars inits.
2467 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2468 CGF.Builder.getInt32(0));
2469 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2470 : CGF.Builder.getInt32(0);
2471 LValue UB =
2472 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2473 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2474 CGF.Builder.getInt32(1));
2475 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2476 CGF.Builder.getInt32(0));
2477 // Loop counter.
2478 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2479 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2480 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2481 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2482 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2483 // Generate condition for loop.
2484 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002485 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002486 // Increment for loop counter.
2487 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002488 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002489 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2490 // Iterate through all sections and emit a switch construct:
2491 // switch (IV) {
2492 // case 0:
2493 // <SectionStmt[0]>;
2494 // break;
2495 // ...
2496 // case <NumSection> - 1:
2497 // <SectionStmt[<NumSection> - 1]>;
2498 // break;
2499 // }
2500 // .omp.sections.exit:
2501 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2502 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2503 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2504 CS == nullptr ? 1 : CS->size());
2505 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002506 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002507 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002508 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2509 CGF.EmitBlock(CaseBB);
2510 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002511 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002512 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002513 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002514 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002515 } else {
2516 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2517 CGF.EmitBlock(CaseBB);
2518 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2519 CGF.EmitStmt(Stmt);
2520 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002521 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002522 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002523 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002524
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002525 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2526 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002527 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002528 // initialization of firstprivate variables and post-update of lastprivate
2529 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002530 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2531 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2532 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002533 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002534 CGF.EmitOMPPrivateClause(S, LoopScope);
2535 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2536 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2537 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002538
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002539 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002540 OpenMPScheduleTy ScheduleKind;
2541 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002542 CGOpenMPRuntime::StaticRTInput StaticInit(
2543 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2544 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002545 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002546 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002547 // UB = min(UB, GlobalUB);
2548 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2549 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2550 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2551 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2552 // IV = LB;
2553 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2554 // while (idx <= UB) { BODY; ++idx; }
2555 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2556 [](CodeGenFunction &) {});
2557 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002558 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002559 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2560 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002561 };
2562 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002563 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002564 // Emit post-update of the reduction variables if IsLastIter != 0.
2565 emitPostUpdateForReductionClause(
2566 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2567 return CGF.Builder.CreateIsNotNull(
2568 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2569 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002570
2571 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2572 if (HasLastprivates)
2573 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002574 S, /*NoFinals=*/false,
2575 CGF.Builder.CreateIsNotNull(
2576 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002577 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002578
2579 bool HasCancel = false;
2580 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2581 HasCancel = OSD->hasCancel();
2582 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2583 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002584 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002585 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2586 HasCancel);
2587 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2588 // clause. Otherwise the barrier will be generated by the codegen for the
2589 // directive.
2590 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002591 // Emit implicit barrier to synchronize threads and avoid data races on
2592 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002593 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2594 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002595 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002596}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002597
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002598void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002599 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002600 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002601 EmitSections(S);
2602 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002603 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002604 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002605 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2606 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002607 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002608}
2609
2610void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002611 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002612 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002613 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002614 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002615 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2616 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002617}
2618
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002619void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002620 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002621 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002622 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002623 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002624 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002625 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002626 // Build a list of copyprivate variables along with helper expressions
2627 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002628 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002629 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002630 DestExprs.append(C->destination_exprs().begin(),
2631 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002632 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002633 AssignmentOps.append(C->assignment_ops().begin(),
2634 C->assignment_ops().end());
2635 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002636 // Emit code for 'single' region along with 'copyprivate' clauses
2637 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2638 Action.Enter(CGF);
2639 OMPPrivateScope SingleScope(CGF);
2640 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2641 CGF.EmitOMPPrivateClause(S, SingleScope);
2642 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002643 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002644 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002645 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002646 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002647 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2648 CopyprivateVars, DestExprs,
2649 SrcExprs, AssignmentOps);
2650 }
2651 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2652 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002653 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002654 CGM.getOpenMPRuntime().emitBarrierCall(
2655 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002656 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002657 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002658}
2659
Alexey Bataev8d690652014-12-04 07:23:53 +00002660void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002661 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2662 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002663 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002665 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002666 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002667}
2668
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002669void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002670 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2671 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002672 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002673 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002674 Expr *Hint = nullptr;
2675 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2676 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002677 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002678 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2679 S.getDirectiveName().getAsString(),
2680 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002681}
2682
Alexey Bataev671605e2015-04-13 05:28:11 +00002683void CodeGenFunction::EmitOMPParallelForDirective(
2684 const OMPParallelForDirective &S) {
2685 // Emit directive as a combined directive that consists of two implicit
2686 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002687 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002688 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002689 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2690 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002691 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002692 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2693 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002694}
2695
Alexander Musmane4e893b2014-09-23 09:33:00 +00002696void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002697 const OMPParallelForSimdDirective &S) {
2698 // Emit directive as a combined directive that consists of two implicit
2699 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002700 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002701 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2702 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002703 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002704 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2705 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002706}
2707
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002708void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002709 const OMPParallelSectionsDirective &S) {
2710 // Emit directive as a combined directive that consists of two implicit
2711 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002712 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2713 CGF.EmitSections(S);
2714 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002715 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2716 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002717}
2718
Alexey Bataev475a7442018-01-12 19:39:11 +00002719void CodeGenFunction::EmitOMPTaskBasedDirective(
2720 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2721 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2722 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002723 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002724 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002725 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002726 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002727 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002728 // Check if the task is final
2729 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2730 // If the condition constant folds and can be elided, try to avoid emitting
2731 // the condition and the dead arm of the if/else.
2732 auto *Cond = Clause->getCondition();
2733 bool CondConstant;
2734 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2735 Data.Final.setInt(CondConstant);
2736 else
2737 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2738 } else {
2739 // By default the task is not final.
2740 Data.Final.setInt(/*IntVal=*/false);
2741 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002742 // Check if the task has 'priority' clause.
2743 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002744 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002745 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002746 Data.Priority.setPointer(EmitScalarConversion(
2747 EmitScalarExpr(Prio), Prio->getType(),
2748 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2749 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002750 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002751 // The first function argument for tasks is a thread id, the second one is a
2752 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002753 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2754 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002755 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002756 auto IRef = C->varlist_begin();
2757 for (auto *IInit : C->private_copies()) {
2758 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2759 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002760 Data.PrivateVars.push_back(*IRef);
2761 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002762 }
2763 ++IRef;
2764 }
2765 }
2766 EmittedAsPrivate.clear();
2767 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002768 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002769 auto IRef = C->varlist_begin();
2770 auto IElemInitRef = C->inits().begin();
2771 for (auto *IInit : C->private_copies()) {
2772 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2773 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002774 Data.FirstprivateVars.push_back(*IRef);
2775 Data.FirstprivateCopies.push_back(IInit);
2776 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002777 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002778 ++IRef;
2779 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002780 }
2781 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002782 // Get list of lastprivate variables (for taskloops).
2783 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2784 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2785 auto IRef = C->varlist_begin();
2786 auto ID = C->destination_exprs().begin();
2787 for (auto *IInit : C->private_copies()) {
2788 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2789 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2790 Data.LastprivateVars.push_back(*IRef);
2791 Data.LastprivateCopies.push_back(IInit);
2792 }
2793 LastprivateDstsOrigs.insert(
2794 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2795 cast<DeclRefExpr>(*IRef)});
2796 ++IRef;
2797 ++ID;
2798 }
2799 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002800 SmallVector<const Expr *, 4> LHSs;
2801 SmallVector<const Expr *, 4> RHSs;
2802 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2803 auto IPriv = C->privates().begin();
2804 auto IRed = C->reduction_ops().begin();
2805 auto ILHS = C->lhs_exprs().begin();
2806 auto IRHS = C->rhs_exprs().begin();
2807 for (const auto *Ref : C->varlists()) {
2808 Data.ReductionVars.emplace_back(Ref);
2809 Data.ReductionCopies.emplace_back(*IPriv);
2810 Data.ReductionOps.emplace_back(*IRed);
2811 LHSs.emplace_back(*ILHS);
2812 RHSs.emplace_back(*IRHS);
2813 std::advance(IPriv, 1);
2814 std::advance(IRed, 1);
2815 std::advance(ILHS, 1);
2816 std::advance(IRHS, 1);
2817 }
2818 }
2819 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2820 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002821 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002822 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2823 for (auto *IRef : C->varlists())
2824 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002825 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2826 CapturedRegion](CodeGenFunction &CGF,
2827 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002828 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002829 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002830 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2831 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002832 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002833 auto *CopyFn = CGF.Builder.CreateLoad(
2834 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2835 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2836 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2837 // Map privates.
2838 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2839 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2840 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002841 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002842 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2843 Address PrivatePtr = CGF.CreateMemTemp(
2844 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2845 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2846 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002847 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002848 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002849 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2850 Address PrivatePtr =
2851 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2852 ".firstpriv.ptr.addr");
2853 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2854 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002855 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002856 for (auto *E : Data.LastprivateVars) {
2857 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2858 Address PrivatePtr =
2859 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2860 ".lastpriv.ptr.addr");
2861 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2862 CallArgs.push_back(PrivatePtr.getPointer());
2863 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002864 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2865 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002866 for (auto &&Pair : LastprivateDstsOrigs) {
2867 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2868 DeclRefExpr DRE(
2869 const_cast<VarDecl *>(OrigVD),
2870 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2871 OrigVD) != nullptr,
2872 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2873 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2874 return CGF.EmitLValue(&DRE).getAddress();
2875 });
2876 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002877 for (auto &&Pair : PrivatePtrs) {
2878 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2879 CGF.getContext().getDeclAlign(Pair.first));
2880 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2881 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002882 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002883 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002884 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002885 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2886 Data.ReductionOps);
2887 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2888 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2889 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2890 RedCG.emitSharedLValue(CGF, Cnt);
2891 RedCG.emitAggregateType(CGF, Cnt);
2892 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2893 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2894 Replacement =
2895 Address(CGF.EmitScalarConversion(
2896 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2897 CGF.getContext().getPointerType(
2898 Data.ReductionCopies[Cnt]->getType()),
2899 SourceLocation()),
2900 Replacement.getAlignment());
2901 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2902 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2903 [Replacement]() { return Replacement; });
2904 // FIXME: This must removed once the runtime library is fixed.
2905 // Emit required threadprivate variables for
2906 // initilizer/combiner/finalizer.
2907 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2908 RedCG, Cnt);
2909 }
2910 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002911 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002912 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002913 SmallVector<const Expr *, 4> InRedVars;
2914 SmallVector<const Expr *, 4> InRedPrivs;
2915 SmallVector<const Expr *, 4> InRedOps;
2916 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2917 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2918 auto IPriv = C->privates().begin();
2919 auto IRed = C->reduction_ops().begin();
2920 auto ITD = C->taskgroup_descriptors().begin();
2921 for (const auto *Ref : C->varlists()) {
2922 InRedVars.emplace_back(Ref);
2923 InRedPrivs.emplace_back(*IPriv);
2924 InRedOps.emplace_back(*IRed);
2925 TaskgroupDescriptors.emplace_back(*ITD);
2926 std::advance(IPriv, 1);
2927 std::advance(IRed, 1);
2928 std::advance(ITD, 1);
2929 }
2930 }
2931 // Privatize in_reduction items here, because taskgroup descriptors must be
2932 // privatized earlier.
2933 OMPPrivateScope InRedScope(CGF);
2934 if (!InRedVars.empty()) {
2935 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2936 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2937 RedCG.emitSharedLValue(CGF, Cnt);
2938 RedCG.emitAggregateType(CGF, Cnt);
2939 // The taskgroup descriptor variable is always implicit firstprivate and
2940 // privatized already during procoessing of the firstprivates.
2941 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2942 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2943 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2944 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2945 Replacement = Address(
2946 CGF.EmitScalarConversion(
2947 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2948 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2949 SourceLocation()),
2950 Replacement.getAlignment());
2951 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2952 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2953 [Replacement]() { return Replacement; });
2954 // FIXME: This must removed once the runtime library is fixed.
2955 // Emit required threadprivate variables for
2956 // initilizer/combiner/finalizer.
2957 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2958 RedCG, Cnt);
2959 }
2960 }
2961 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002962
2963 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002964 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002965 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002966 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2967 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2968 Data.NumberOfParts);
2969 OMPLexicalScope Scope(*this, S);
2970 TaskGen(*this, OutlinedFn, Data);
2971}
2972
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002973static ImplicitParamDecl *
2974createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
2975 QualType Ty, CapturedDecl *CD) {
2976 auto *OrigVD = ImplicitParamDecl::Create(
2977 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2978 auto *OrigRef =
2979 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2980 /*RefersToEnclosingVariableOrCapture=*/false,
2981 SourceLocation(), Ty, VK_LValue);
2982 auto *PrivateVD = ImplicitParamDecl::Create(
2983 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2984 auto *PrivateRef = DeclRefExpr::Create(
2985 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
2986 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(), Ty,
2987 VK_LValue);
2988 QualType ElemType = C.getBaseElementType(Ty);
2989 auto *InitVD =
2990 ImplicitParamDecl::Create(C, CD, SourceLocation(), /*Id=*/nullptr,
2991 ElemType, ImplicitParamDecl::Other);
2992 auto *InitRef =
2993 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2994 /*RefersToEnclosingVariableOrCapture=*/false,
2995 SourceLocation(), ElemType, VK_LValue);
2996 PrivateVD->setInitStyle(VarDecl::CInit);
2997 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2998 InitRef, /*BasePath=*/nullptr,
2999 VK_RValue));
3000 Data.FirstprivateVars.emplace_back(OrigRef);
3001 Data.FirstprivateCopies.emplace_back(PrivateRef);
3002 Data.FirstprivateInits.emplace_back(InitRef);
3003 return OrigVD;
3004}
3005
3006void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3007 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3008 OMPTargetDataInfo &InputInfo) {
3009 // Emit outlined function for task construct.
3010 auto CS = S.getCapturedStmt(OMPD_task);
3011 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3012 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3013 auto *I = CS->getCapturedDecl()->param_begin();
3014 auto *PartId = std::next(I);
3015 auto *TaskT = std::next(I, 4);
3016 OMPTaskDataTy Data;
3017 // The task is not final.
3018 Data.Final.setInt(/*IntVal=*/false);
3019 // Get list of firstprivate variables.
3020 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3021 auto IRef = C->varlist_begin();
3022 auto IElemInitRef = C->inits().begin();
3023 for (auto *IInit : C->private_copies()) {
3024 Data.FirstprivateVars.push_back(*IRef);
3025 Data.FirstprivateCopies.push_back(IInit);
3026 Data.FirstprivateInits.push_back(*IElemInitRef);
3027 ++IRef;
3028 ++IElemInitRef;
3029 }
3030 }
3031 OMPPrivateScope TargetScope(*this);
3032 VarDecl *BPVD = nullptr;
3033 VarDecl *PVD = nullptr;
3034 VarDecl *SVD = nullptr;
3035 if (InputInfo.NumberOfTargetItems > 0) {
3036 auto *CD = CapturedDecl::Create(
3037 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3038 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3039 QualType BaseAndPointersType = getContext().getConstantArrayType(
3040 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3041 /*IndexTypeQuals=*/0);
3042 BPVD = createImplicitFirstprivateForType(getContext(), Data,
3043 BaseAndPointersType, CD);
3044 PVD = createImplicitFirstprivateForType(getContext(), Data,
3045 BaseAndPointersType, CD);
3046 QualType SizesType = getContext().getConstantArrayType(
3047 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3048 /*IndexTypeQuals=*/0);
3049 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD);
3050 TargetScope.addPrivate(
3051 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3052 TargetScope.addPrivate(PVD,
3053 [&InputInfo]() { return InputInfo.PointersArray; });
3054 TargetScope.addPrivate(SVD,
3055 [&InputInfo]() { return InputInfo.SizesArray; });
3056 }
3057 (void)TargetScope.Privatize();
3058 // Build list of dependences.
3059 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3060 for (auto *IRef : C->varlists())
3061 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3062 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3063 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3064 // Set proper addresses for generated private copies.
3065 OMPPrivateScope Scope(CGF);
3066 if (!Data.FirstprivateVars.empty()) {
3067 enum { PrivatesParam = 2, CopyFnParam = 3 };
3068 auto *CopyFn = CGF.Builder.CreateLoad(
3069 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3070 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3071 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3072 // Map privates.
3073 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3074 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3075 CallArgs.push_back(PrivatesPtr);
3076 for (auto *E : Data.FirstprivateVars) {
3077 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3078 Address PrivatePtr =
3079 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3080 ".firstpriv.ptr.addr");
3081 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3082 CallArgs.push_back(PrivatePtr.getPointer());
3083 }
3084 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3085 CopyFn, CallArgs);
3086 for (auto &&Pair : PrivatePtrs) {
3087 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3088 CGF.getContext().getDeclAlign(Pair.first));
3089 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3090 }
3091 }
3092 // Privatize all private variables except for in_reduction items.
3093 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003094 if (InputInfo.NumberOfTargetItems > 0) {
3095 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3096 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3097 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3098 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3099 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3100 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3101 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003102
3103 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003104 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003105 BodyGen(CGF);
3106 };
3107 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3108 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3109 Data.NumberOfParts);
3110 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3111 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3112 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3113 SourceLocation());
3114
3115 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3116 SharedsTy, CapturedStruct, &IfCond, Data);
3117}
3118
Alexey Bataev7292c292016-04-25 12:22:29 +00003119void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3120 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003121 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003122 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003123 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003124 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003125 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3126 if (C->getNameModifier() == OMPD_unknown ||
3127 C->getNameModifier() == OMPD_task) {
3128 IfCond = C->getCondition();
3129 break;
3130 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003131 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003132
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003133 OMPTaskDataTy Data;
3134 // Check if we should emit tied or untied task.
3135 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003136 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3137 CGF.EmitStmt(CS->getCapturedStmt());
3138 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003139 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003140 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003141 const OMPTaskDataTy &Data) {
3142 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3143 SharedsTy, CapturedStruct, IfCond,
3144 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003145 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003146 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003147}
3148
Alexey Bataev9f797f32015-02-05 05:57:51 +00003149void CodeGenFunction::EmitOMPTaskyieldDirective(
3150 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003151 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003152}
3153
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003154void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003155 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003156}
3157
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003158void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3159 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003160}
3161
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003162void CodeGenFunction::EmitOMPTaskgroupDirective(
3163 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003164 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3165 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003166 if (const Expr *E = S.getReductionRef()) {
3167 SmallVector<const Expr *, 4> LHSs;
3168 SmallVector<const Expr *, 4> RHSs;
3169 OMPTaskDataTy Data;
3170 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3171 auto IPriv = C->privates().begin();
3172 auto IRed = C->reduction_ops().begin();
3173 auto ILHS = C->lhs_exprs().begin();
3174 auto IRHS = C->rhs_exprs().begin();
3175 for (const auto *Ref : C->varlists()) {
3176 Data.ReductionVars.emplace_back(Ref);
3177 Data.ReductionCopies.emplace_back(*IPriv);
3178 Data.ReductionOps.emplace_back(*IRed);
3179 LHSs.emplace_back(*ILHS);
3180 RHSs.emplace_back(*IRHS);
3181 std::advance(IPriv, 1);
3182 std::advance(IRed, 1);
3183 std::advance(ILHS, 1);
3184 std::advance(IRHS, 1);
3185 }
3186 }
3187 llvm::Value *ReductionDesc =
3188 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3189 LHSs, RHSs, Data);
3190 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3191 CGF.EmitVarDecl(*VD);
3192 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3193 /*Volatile=*/false, E->getType());
3194 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003195 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003196 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003197 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003198 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3199}
3200
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003201void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003202 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003203 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003204 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3205 FlushClause->varlist_end());
3206 }
3207 return llvm::None;
3208 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003209}
3210
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003211void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3212 const CodeGenLoopTy &CodeGenLoop,
3213 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003214 // Emit the loop iteration variable.
3215 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3216 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3217 EmitVarDecl(*IVDecl);
3218
3219 // Emit the iterations count variable.
3220 // If it is not a variable, Sema decided to calculate iterations count on each
3221 // iteration (e.g., it is foldable into a constant).
3222 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3223 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3224 // Emit calculation of the iterations count.
3225 EmitIgnoredExpr(S.getCalcLastIteration());
3226 }
3227
3228 auto &RT = CGM.getOpenMPRuntime();
3229
Carlo Bertolli962bb802017-01-03 18:24:42 +00003230 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003231 // Check pre-condition.
3232 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003233 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003234 // Skip the entire loop if we don't meet the precondition.
3235 // If the condition constant folds and can be elided, avoid emitting the
3236 // whole loop.
3237 bool CondConstant;
3238 llvm::BasicBlock *ContBlock = nullptr;
3239 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3240 if (!CondConstant)
3241 return;
3242 } else {
3243 auto *ThenBlock = createBasicBlock("omp.precond.then");
3244 ContBlock = createBasicBlock("omp.precond.end");
3245 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3246 getProfileCount(&S));
3247 EmitBlock(ThenBlock);
3248 incrementProfileCounter(&S);
3249 }
3250
Alexey Bataev617db5f2017-12-04 15:38:33 +00003251 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003252 // Emit 'then' code.
3253 {
3254 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003255
3256 LValue LB = EmitOMPHelperVar(
3257 *this, cast<DeclRefExpr>(
3258 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3259 ? S.getCombinedLowerBoundVariable()
3260 : S.getLowerBoundVariable())));
3261 LValue UB = EmitOMPHelperVar(
3262 *this, cast<DeclRefExpr>(
3263 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3264 ? S.getCombinedUpperBoundVariable()
3265 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003266 LValue ST =
3267 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3268 LValue IL =
3269 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3270
3271 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003272 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003273 // Emit implicit barrier to synchronize threads and avoid data races
3274 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003275 // lastprivate variables.
3276 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003277 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3278 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003279 }
3280 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003281 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003282 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3283 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003284 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003285 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003286 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003287 (void)LoopScope.Privatize();
3288
3289 // Detect the distribute schedule kind and chunk.
3290 llvm::Value *Chunk = nullptr;
3291 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3292 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3293 ScheduleKind = C->getDistScheduleKind();
3294 if (const auto *Ch = C->getChunkSize()) {
3295 Chunk = EmitScalarExpr(Ch);
3296 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003297 S.getIterationVariable()->getType(),
3298 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003299 }
3300 }
3301 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3302 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3303
3304 // OpenMP [2.10.8, distribute Construct, Description]
3305 // If dist_schedule is specified, kind must be static. If specified,
3306 // iterations are divided into chunks of size chunk_size, chunks are
3307 // assigned to the teams of the league in a round-robin fashion in the
3308 // order of the team number. When no chunk_size is specified, the
3309 // iteration space is divided into chunks that are approximately equal
3310 // in size, and at most one chunk is distributed to each team of the
3311 // league. The size of the chunks is unspecified in this case.
3312 if (RT.isStaticNonchunked(ScheduleKind,
3313 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003314 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3315 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003316 CGOpenMPRuntime::StaticRTInput StaticInit(
3317 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3318 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003319 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003320 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003321 auto LoopExit =
3322 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3323 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003324 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3325 ? S.getCombinedEnsureUpperBound()
3326 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003327 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003328 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3329 ? S.getCombinedInit()
3330 : S.getInit());
3331
3332 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3333 ? S.getCombinedCond()
3334 : S.getCond();
3335
3336 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003337 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003338 // when combined with 'for' (e.g. as in 'distribute parallel for')
3339 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3340 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3341 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3342 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003343 },
3344 [](CodeGenFunction &) {});
3345 EmitBlock(LoopExit.getBlock());
3346 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003347 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003348 } else {
3349 // Emit the outer loop, which requests its work chunk [LB..UB] from
3350 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003351 const OMPLoopArguments LoopArguments = {
3352 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3353 Chunk};
3354 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3355 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003356 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003357 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3358 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3359 return CGF.Builder.CreateIsNotNull(
3360 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3361 });
3362 }
3363 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3364 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3365 isOpenMPSimdDirective(S.getDirectiveKind())) {
3366 ReductionKind = OMPD_parallel_for_simd;
3367 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3368 ReductionKind = OMPD_parallel_for;
3369 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3370 ReductionKind = OMPD_simd;
3371 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3372 S.hasClausesOfKind<OMPReductionClause>()) {
3373 llvm_unreachable(
3374 "No reduction clauses is allowed in distribute directive.");
3375 }
3376 EmitOMPReductionClauseFinal(S, ReductionKind);
3377 // Emit post-update of the reduction variables if IsLastIter != 0.
3378 emitPostUpdateForReductionClause(
3379 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3380 return CGF.Builder.CreateIsNotNull(
3381 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3382 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003383 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003384 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003385 EmitOMPLastprivateClauseFinal(
3386 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003387 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3388 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003389 }
3390
3391 // We're now done with the loop, so jump to the continuation block.
3392 if (ContBlock) {
3393 EmitBranch(ContBlock);
3394 EmitBlock(ContBlock, true);
3395 }
3396 }
3397}
3398
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003399void CodeGenFunction::EmitOMPDistributeDirective(
3400 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003401 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003402
3403 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003404 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003405 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003406 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003407}
3408
Alexey Bataev5f600d62015-09-29 03:48:57 +00003409static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3410 const CapturedStmt *S) {
3411 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3412 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3413 CGF.CapturedStmtInfo = &CapStmtInfo;
3414 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3415 Fn->addFnAttr(llvm::Attribute::NoInline);
3416 return Fn;
3417}
3418
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003419void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003420 if (S.hasClausesOfKind<OMPDependClause>()) {
3421 assert(!S.getAssociatedStmt() &&
3422 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003423 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3424 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003425 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003426 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003427 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003428 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3429 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003430 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003431 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003432 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3433 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3434 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003435 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3436 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003437 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003438 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003439 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003440 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003441 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003442 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003443 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003444}
3445
Alexey Bataevb57056f2015-01-22 06:17:56 +00003446static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003447 QualType SrcType, QualType DestType,
3448 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003449 assert(CGF.hasScalarEvaluationKind(DestType) &&
3450 "DestType must have scalar evaluation kind.");
3451 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3452 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003453 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3454 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003455 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003456 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003457}
3458
3459static CodeGenFunction::ComplexPairTy
3460convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003461 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003462 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3463 "DestType must have complex evaluation kind.");
3464 CodeGenFunction::ComplexPairTy ComplexVal;
3465 if (Val.isScalar()) {
3466 // Convert the input element to the element type of the complex.
3467 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003468 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3469 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003470 ComplexVal = CodeGenFunction::ComplexPairTy(
3471 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3472 } else {
3473 assert(Val.isComplex() && "Must be a scalar or complex.");
3474 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3475 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3476 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003477 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003478 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003479 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003480 }
3481 return ComplexVal;
3482}
3483
Alexey Bataev5e018f92015-04-23 06:35:10 +00003484static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3485 LValue LVal, RValue RVal) {
3486 if (LVal.isGlobalReg()) {
3487 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3488 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003489 CGF.EmitAtomicStore(RVal, LVal,
3490 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3491 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003492 LVal.isVolatile(), /*IsInit=*/false);
3493 }
3494}
3495
Alexey Bataev8524d152016-01-21 12:35:58 +00003496void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3497 QualType RValTy, SourceLocation Loc) {
3498 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003499 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003500 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3501 *this, RVal, RValTy, LVal.getType(), Loc)),
3502 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003503 break;
3504 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003505 EmitStoreOfComplex(
3506 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003507 /*isInit=*/false);
3508 break;
3509 case TEK_Aggregate:
3510 llvm_unreachable("Must be a scalar or complex.");
3511 }
3512}
3513
Alexey Bataevb57056f2015-01-22 06:17:56 +00003514static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3515 const Expr *X, const Expr *V,
3516 SourceLocation Loc) {
3517 // v = x;
3518 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3519 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3520 LValue XLValue = CGF.EmitLValue(X);
3521 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003522 RValue Res = XLValue.isGlobalReg()
3523 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003524 : CGF.EmitAtomicLoad(
3525 XLValue, Loc,
3526 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3527 : llvm::AtomicOrdering::Monotonic,
3528 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003529 // OpenMP, 2.12.6, atomic Construct
3530 // Any atomic construct with a seq_cst clause forces the atomically
3531 // performed operation to include an implicit flush operation without a
3532 // list.
3533 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003534 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003535 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003536}
3537
Alexey Bataevb8329262015-02-27 06:33:30 +00003538static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3539 const Expr *X, const Expr *E,
3540 SourceLocation Loc) {
3541 // x = expr;
3542 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003543 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003544 // OpenMP, 2.12.6, atomic Construct
3545 // Any atomic construct with a seq_cst clause forces the atomically
3546 // performed operation to include an implicit flush operation without a
3547 // list.
3548 if (IsSeqCst)
3549 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3550}
3551
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003552static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3553 RValue Update,
3554 BinaryOperatorKind BO,
3555 llvm::AtomicOrdering AO,
3556 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003557 auto &Context = CGF.CGM.getContext();
3558 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003559 // expression is simple and atomic is allowed for the given type for the
3560 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003561 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003562 !Update.getScalarVal()->getType()->isIntegerTy() ||
3563 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3564 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003565 X.getAddress().getElementType())) ||
3566 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003567 !Context.getTargetInfo().hasBuiltinAtomic(
3568 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003569 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003570
3571 llvm::AtomicRMWInst::BinOp RMWOp;
3572 switch (BO) {
3573 case BO_Add:
3574 RMWOp = llvm::AtomicRMWInst::Add;
3575 break;
3576 case BO_Sub:
3577 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003578 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003579 RMWOp = llvm::AtomicRMWInst::Sub;
3580 break;
3581 case BO_And:
3582 RMWOp = llvm::AtomicRMWInst::And;
3583 break;
3584 case BO_Or:
3585 RMWOp = llvm::AtomicRMWInst::Or;
3586 break;
3587 case BO_Xor:
3588 RMWOp = llvm::AtomicRMWInst::Xor;
3589 break;
3590 case BO_LT:
3591 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3592 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3593 : llvm::AtomicRMWInst::Max)
3594 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3595 : llvm::AtomicRMWInst::UMax);
3596 break;
3597 case BO_GT:
3598 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3599 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3600 : llvm::AtomicRMWInst::Min)
3601 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3602 : llvm::AtomicRMWInst::UMin);
3603 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003604 case BO_Assign:
3605 RMWOp = llvm::AtomicRMWInst::Xchg;
3606 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003607 case BO_Mul:
3608 case BO_Div:
3609 case BO_Rem:
3610 case BO_Shl:
3611 case BO_Shr:
3612 case BO_LAnd:
3613 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003614 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003615 case BO_PtrMemD:
3616 case BO_PtrMemI:
3617 case BO_LE:
3618 case BO_GE:
3619 case BO_EQ:
3620 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003621 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003622 case BO_AddAssign:
3623 case BO_SubAssign:
3624 case BO_AndAssign:
3625 case BO_OrAssign:
3626 case BO_XorAssign:
3627 case BO_MulAssign:
3628 case BO_DivAssign:
3629 case BO_RemAssign:
3630 case BO_ShlAssign:
3631 case BO_ShrAssign:
3632 case BO_Comma:
3633 llvm_unreachable("Unsupported atomic update operation");
3634 }
3635 auto *UpdateVal = Update.getScalarVal();
3636 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3637 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003638 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003639 X.getType()->hasSignedIntegerRepresentation());
3640 }
John McCall7f416cc2015-09-08 08:05:57 +00003641 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003642 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003643}
3644
Alexey Bataev5e018f92015-04-23 06:35:10 +00003645std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003646 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3647 llvm::AtomicOrdering AO, SourceLocation Loc,
3648 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3649 // Update expressions are allowed to have the following forms:
3650 // x binop= expr; -> xrval + expr;
3651 // x++, ++x -> xrval + 1;
3652 // x--, --x -> xrval - 1;
3653 // x = x binop expr; -> xrval binop expr
3654 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003655 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3656 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003657 if (X.isGlobalReg()) {
3658 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3659 // 'xrval'.
3660 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3661 } else {
3662 // Perform compare-and-swap procedure.
3663 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003664 }
3665 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003666 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003667}
3668
3669static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3670 const Expr *X, const Expr *E,
3671 const Expr *UE, bool IsXLHSInRHSPart,
3672 SourceLocation Loc) {
3673 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3674 "Update expr in 'atomic update' must be a binary operator.");
3675 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3676 // Update expressions are allowed to have the following forms:
3677 // x binop= expr; -> xrval + expr;
3678 // x++, ++x -> xrval + 1;
3679 // x--, --x -> xrval - 1;
3680 // x = x binop expr; -> xrval binop expr
3681 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003682 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003683 LValue XLValue = CGF.EmitLValue(X);
3684 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003685 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3686 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003687 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3688 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3689 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3690 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3691 auto Gen =
3692 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3693 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3694 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3695 return CGF.EmitAnyExpr(UE);
3696 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003697 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3698 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3699 // OpenMP, 2.12.6, atomic Construct
3700 // Any atomic construct with a seq_cst clause forces the atomically
3701 // performed operation to include an implicit flush operation without a
3702 // list.
3703 if (IsSeqCst)
3704 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3705}
3706
3707static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003708 QualType SourceType, QualType ResType,
3709 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003710 switch (CGF.getEvaluationKind(ResType)) {
3711 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003712 return RValue::get(
3713 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003714 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003715 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003716 return RValue::getComplex(Res.first, Res.second);
3717 }
3718 case TEK_Aggregate:
3719 break;
3720 }
3721 llvm_unreachable("Must be a scalar or complex.");
3722}
3723
3724static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3725 bool IsPostfixUpdate, const Expr *V,
3726 const Expr *X, const Expr *E,
3727 const Expr *UE, bool IsXLHSInRHSPart,
3728 SourceLocation Loc) {
3729 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3730 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3731 RValue NewVVal;
3732 LValue VLValue = CGF.EmitLValue(V);
3733 LValue XLValue = CGF.EmitLValue(X);
3734 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003735 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3736 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003737 QualType NewVValType;
3738 if (UE) {
3739 // 'x' is updated with some additional value.
3740 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3741 "Update expr in 'atomic capture' must be a binary operator.");
3742 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3743 // Update expressions are allowed to have the following forms:
3744 // x binop= expr; -> xrval + expr;
3745 // x++, ++x -> xrval + 1;
3746 // x--, --x -> xrval - 1;
3747 // x = x binop expr; -> xrval binop expr
3748 // x = expr Op x; - > expr binop xrval;
3749 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3750 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3751 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3752 NewVValType = XRValExpr->getType();
3753 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3754 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003755 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003756 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3757 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3758 RValue Res = CGF.EmitAnyExpr(UE);
3759 NewVVal = IsPostfixUpdate ? XRValue : Res;
3760 return Res;
3761 };
3762 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3763 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3764 if (Res.first) {
3765 // 'atomicrmw' instruction was generated.
3766 if (IsPostfixUpdate) {
3767 // Use old value from 'atomicrmw'.
3768 NewVVal = Res.second;
3769 } else {
3770 // 'atomicrmw' does not provide new value, so evaluate it using old
3771 // value of 'x'.
3772 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3773 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3774 NewVVal = CGF.EmitAnyExpr(UE);
3775 }
3776 }
3777 } else {
3778 // 'x' is simply rewritten with some 'expr'.
3779 NewVValType = X->getType().getNonReferenceType();
3780 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003781 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003782 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003783 NewVVal = XRValue;
3784 return ExprRValue;
3785 };
3786 // Try to perform atomicrmw xchg, otherwise simple exchange.
3787 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3788 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3789 Loc, Gen);
3790 if (Res.first) {
3791 // 'atomicrmw' instruction was generated.
3792 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3793 }
3794 }
3795 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003796 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003797 // OpenMP, 2.12.6, atomic Construct
3798 // Any atomic construct with a seq_cst clause forces the atomically
3799 // performed operation to include an implicit flush operation without a
3800 // list.
3801 if (IsSeqCst)
3802 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3803}
3804
Alexey Bataevb57056f2015-01-22 06:17:56 +00003805static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003806 bool IsSeqCst, bool IsPostfixUpdate,
3807 const Expr *X, const Expr *V, const Expr *E,
3808 const Expr *UE, bool IsXLHSInRHSPart,
3809 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003810 switch (Kind) {
3811 case OMPC_read:
3812 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3813 break;
3814 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003815 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3816 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003817 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003818 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003819 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3820 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003821 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003822 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3823 IsXLHSInRHSPart, Loc);
3824 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003825 case OMPC_if:
3826 case OMPC_final:
3827 case OMPC_num_threads:
3828 case OMPC_private:
3829 case OMPC_firstprivate:
3830 case OMPC_lastprivate:
3831 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003832 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003833 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003834 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003835 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003836 case OMPC_collapse:
3837 case OMPC_default:
3838 case OMPC_seq_cst:
3839 case OMPC_shared:
3840 case OMPC_linear:
3841 case OMPC_aligned:
3842 case OMPC_copyin:
3843 case OMPC_copyprivate:
3844 case OMPC_flush:
3845 case OMPC_proc_bind:
3846 case OMPC_schedule:
3847 case OMPC_ordered:
3848 case OMPC_nowait:
3849 case OMPC_untied:
3850 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003851 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003852 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003853 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003854 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003855 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003856 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003857 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003858 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003859 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003860 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003861 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003862 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003863 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003864 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003865 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003866 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003867 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003868 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003869 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003870 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003871 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3872 }
3873}
3874
3875void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003876 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003877 OpenMPClauseKind Kind = OMPC_unknown;
3878 for (auto *C : S.clauses()) {
3879 // Find first clause (skip seq_cst clause, if it is first).
3880 if (C->getClauseKind() != OMPC_seq_cst) {
3881 Kind = C->getClauseKind();
3882 break;
3883 }
3884 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003885
Alexey Bataev475a7442018-01-12 19:39:11 +00003886 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003887 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003888 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003889 }
3890 // Processing for statements under 'atomic capture'.
3891 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3892 for (const auto *C : Compound->body()) {
3893 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3894 enterFullExpression(EWC);
3895 }
3896 }
3897 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003898
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003899 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3900 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003901 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003902 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3903 S.getV(), S.getExpr(), S.getUpdateExpr(),
3904 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003905 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003906 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003907 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003908}
3909
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003910static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3911 const OMPExecutableDirective &S,
3912 const RegionCodeGenTy &CodeGen) {
3913 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3914 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003915
Samuel Antaoee8fb302016-01-06 13:42:12 +00003916 llvm::Function *Fn = nullptr;
3917 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003918
Samuel Antaobed3c462015-10-02 16:14:20 +00003919 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003920 // Check for the at most one if clause associated with the target region.
3921 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3922 if (C->getNameModifier() == OMPD_unknown ||
3923 C->getNameModifier() == OMPD_target) {
3924 IfCond = C->getCondition();
3925 break;
3926 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003927 }
3928
3929 // Check if we have any device clause associated with the directive.
3930 const Expr *Device = nullptr;
3931 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3932 Device = C->getDevice();
3933 }
3934
Samuel Antaoee8fb302016-01-06 13:42:12 +00003935 // Check if we have an if clause whose conditional always evaluates to false
3936 // or if we do not have any targets specified. If so the target region is not
3937 // an offload entry point.
3938 bool IsOffloadEntry = true;
3939 if (IfCond) {
3940 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003941 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 IsOffloadEntry = false;
3943 }
3944 if (CGM.getLangOpts().OMPTargetTriples.empty())
3945 IsOffloadEntry = false;
3946
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003947 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948 StringRef ParentName;
3949 // In case we have Ctors/Dtors we use the complete type variant to produce
3950 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003951 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003952 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003953 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003954 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3955 else
3956 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003957 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003958
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003959 // Emit target region as a standalone region.
3960 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3961 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003962 OMPLexicalScope Scope(CGF, S, OMPD_task);
3963 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003964}
3965
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003966static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3967 PrePostActionTy &Action) {
3968 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3969 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3970 CGF.EmitOMPPrivateClause(S, PrivateScope);
3971 (void)PrivateScope.Privatize();
3972
3973 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003974 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003975}
3976
3977void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3978 StringRef ParentName,
3979 const OMPTargetDirective &S) {
3980 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3981 emitTargetRegion(CGF, S, Action);
3982 };
3983 llvm::Function *Fn;
3984 llvm::Constant *Addr;
3985 // Emit target region as a standalone region.
3986 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3987 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3988 assert(Fn && Addr && "Target device function emission failed.");
3989}
3990
3991void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3992 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3993 emitTargetRegion(CGF, S, Action);
3994 };
3995 emitCommonOMPTargetDirective(*this, S, CodeGen);
3996}
3997
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003998static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3999 const OMPExecutableDirective &S,
4000 OpenMPDirectiveKind InnermostKind,
4001 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004002 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4003 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4004 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004005
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004006 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4007 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004008 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004009 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4010 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004011
Carlo Bertollic6872252016-04-04 15:55:02 +00004012 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4013 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004014 }
4015
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004016 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004017 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4018 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004019 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4020 CapturedVars);
4021}
4022
4023void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004024 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004025 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004026 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004027 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4028 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004030 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004031 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004032 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004033 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004034 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004035 emitPostUpdateForReductionClause(
4036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004037}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004038
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004039static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4040 const OMPTargetTeamsDirective &S) {
4041 auto *CS = S.getCapturedStmt(OMPD_teams);
4042 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004043 // Emit teams region as a standalone region.
4044 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4045 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4046 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4047 CGF.EmitOMPPrivateClause(S, PrivateScope);
4048 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4049 (void)PrivateScope.Privatize();
4050 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004051 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004052 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004053 };
4054 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004055 emitPostUpdateForReductionClause(
4056 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004057}
4058
4059void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4060 CodeGenModule &CGM, StringRef ParentName,
4061 const OMPTargetTeamsDirective &S) {
4062 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4063 emitTargetTeamsRegion(CGF, Action, S);
4064 };
4065 llvm::Function *Fn;
4066 llvm::Constant *Addr;
4067 // Emit target region as a standalone region.
4068 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4069 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4070 assert(Fn && Addr && "Target device function emission failed.");
4071}
4072
4073void CodeGenFunction::EmitOMPTargetTeamsDirective(
4074 const OMPTargetTeamsDirective &S) {
4075 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4076 emitTargetTeamsRegion(CGF, Action, S);
4077 };
4078 emitCommonOMPTargetDirective(*this, S, CodeGen);
4079}
4080
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004081static void
4082emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4083 const OMPTargetTeamsDistributeDirective &S) {
4084 Action.Enter(CGF);
4085 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4086 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4087 };
4088
4089 // Emit teams region as a standalone region.
4090 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4091 PrePostActionTy &) {
4092 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4093 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4094 (void)PrivateScope.Privatize();
4095 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4096 CodeGenDistribute);
4097 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4098 };
4099 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4100 emitPostUpdateForReductionClause(CGF, S,
4101 [](CodeGenFunction &) { return nullptr; });
4102}
4103
4104void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4105 CodeGenModule &CGM, StringRef ParentName,
4106 const OMPTargetTeamsDistributeDirective &S) {
4107 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4108 emitTargetTeamsDistributeRegion(CGF, Action, S);
4109 };
4110 llvm::Function *Fn;
4111 llvm::Constant *Addr;
4112 // Emit target region as a standalone region.
4113 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4114 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4115 assert(Fn && Addr && "Target device function emission failed.");
4116}
4117
4118void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4119 const OMPTargetTeamsDistributeDirective &S) {
4120 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4121 emitTargetTeamsDistributeRegion(CGF, Action, S);
4122 };
4123 emitCommonOMPTargetDirective(*this, S, CodeGen);
4124}
4125
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004126static void emitTargetTeamsDistributeSimdRegion(
4127 CodeGenFunction &CGF, PrePostActionTy &Action,
4128 const OMPTargetTeamsDistributeSimdDirective &S) {
4129 Action.Enter(CGF);
4130 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4131 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4132 };
4133
4134 // Emit teams region as a standalone region.
4135 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4136 PrePostActionTy &) {
4137 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4138 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4139 (void)PrivateScope.Privatize();
4140 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4141 CodeGenDistribute);
4142 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4143 };
4144 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4145 emitPostUpdateForReductionClause(CGF, S,
4146 [](CodeGenFunction &) { return nullptr; });
4147}
4148
4149void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4150 CodeGenModule &CGM, StringRef ParentName,
4151 const OMPTargetTeamsDistributeSimdDirective &S) {
4152 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4153 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4154 };
4155 llvm::Function *Fn;
4156 llvm::Constant *Addr;
4157 // Emit target region as a standalone region.
4158 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4159 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4160 assert(Fn && Addr && "Target device function emission failed.");
4161}
4162
4163void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4164 const OMPTargetTeamsDistributeSimdDirective &S) {
4165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4166 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4167 };
4168 emitCommonOMPTargetDirective(*this, S, CodeGen);
4169}
4170
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004171void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4172 const OMPTeamsDistributeDirective &S) {
4173
4174 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4175 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4176 };
4177
4178 // Emit teams region as a standalone region.
4179 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4180 PrePostActionTy &) {
4181 OMPPrivateScope PrivateScope(CGF);
4182 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4183 (void)PrivateScope.Privatize();
4184 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4185 CodeGenDistribute);
4186 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4187 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004188 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004189 emitPostUpdateForReductionClause(*this, S,
4190 [](CodeGenFunction &) { return nullptr; });
4191}
4192
Alexey Bataev999277a2017-12-06 14:31:09 +00004193void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4194 const OMPTeamsDistributeSimdDirective &S) {
4195 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4196 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4197 };
4198
4199 // Emit teams region as a standalone region.
4200 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4201 PrePostActionTy &) {
4202 OMPPrivateScope PrivateScope(CGF);
4203 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4204 (void)PrivateScope.Privatize();
4205 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4206 CodeGenDistribute);
4207 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4208 };
4209 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4210 emitPostUpdateForReductionClause(*this, S,
4211 [](CodeGenFunction &) { return nullptr; });
4212}
4213
Carlo Bertolli62fae152017-11-20 20:46:39 +00004214void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4215 const OMPTeamsDistributeParallelForDirective &S) {
4216 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4217 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4218 S.getDistInc());
4219 };
4220
4221 // Emit teams region as a standalone region.
4222 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4223 PrePostActionTy &) {
4224 OMPPrivateScope PrivateScope(CGF);
4225 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4226 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004227 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4228 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004229 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4230 };
4231 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4232 emitPostUpdateForReductionClause(*this, S,
4233 [](CodeGenFunction &) { return nullptr; });
4234}
4235
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004236void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4237 const OMPTeamsDistributeParallelForSimdDirective &S) {
4238 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4239 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4240 S.getDistInc());
4241 };
4242
4243 // Emit teams region as a standalone region.
4244 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4245 PrePostActionTy &) {
4246 OMPPrivateScope PrivateScope(CGF);
4247 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4248 (void)PrivateScope.Privatize();
4249 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4250 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4251 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4252 };
4253 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4254 emitPostUpdateForReductionClause(*this, S,
4255 [](CodeGenFunction &) { return nullptr; });
4256}
4257
Carlo Bertolli52978c32018-01-03 21:12:44 +00004258static void emitTargetTeamsDistributeParallelForRegion(
4259 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4260 PrePostActionTy &Action) {
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](
Alexey Bataev475a7442018-01-12 19:39:11 +00004424 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004425 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004426 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004427 };
4428
4429 // Codegen that selects wheather to generate the privatization code or not.
4430 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4431 &InnermostCodeGen](CodeGenFunction &CGF,
4432 PrePostActionTy &Action) {
4433 RegionCodeGenTy RCG(InnermostCodeGen);
4434 PrivatizeDevicePointers = false;
4435
4436 // Call the pre-action to change the status of PrivatizeDevicePointers if
4437 // needed.
4438 Action.Enter(CGF);
4439
4440 if (PrivatizeDevicePointers) {
4441 OMPPrivateScope PrivateScope(CGF);
4442 // Emit all instances of the use_device_ptr clause.
4443 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4444 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4445 Info.CaptureDeviceAddrMap);
4446 (void)PrivateScope.Privatize();
4447 RCG(CGF);
4448 } else
4449 RCG(CGF);
4450 };
4451
4452 // Forward the provided action to the privatization codegen.
4453 RegionCodeGenTy PrivRCG(PrivCodeGen);
4454 PrivRCG.setAction(Action);
4455
4456 // Notwithstanding the body of the region is emitted as inlined directive,
4457 // we don't use an inline scope as changes in the references inside the
4458 // region are expected to be visible outside, so we do not privative them.
4459 OMPLexicalScope Scope(CGF, S);
4460 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4461 PrivRCG);
4462 };
4463
4464 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004465
4466 // If we don't have target devices, don't bother emitting the data mapping
4467 // code.
4468 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004469 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004470 return;
4471 }
4472
4473 // Check if we have any if clause associated with the directive.
4474 const Expr *IfCond = nullptr;
4475 if (auto *C = S.getSingleClause<OMPIfClause>())
4476 IfCond = C->getCondition();
4477
4478 // Check if we have any device clause associated with the directive.
4479 const Expr *Device = nullptr;
4480 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4481 Device = C->getDevice();
4482
Samuel Antaocc10b852016-07-28 14:23:26 +00004483 // Set the action to signal privatization of device pointers.
4484 RCG.setAction(PrivAction);
4485
4486 // Emit region code.
4487 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4488 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004489}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004490
Samuel Antaodf67fc42016-01-19 19:15:56 +00004491void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4492 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004493 // If we don't have target devices, don't bother emitting the data mapping
4494 // code.
4495 if (CGM.getLangOpts().OMPTargetTriples.empty())
4496 return;
4497
4498 // Check if we have any if clause associated with the directive.
4499 const Expr *IfCond = nullptr;
4500 if (auto *C = S.getSingleClause<OMPIfClause>())
4501 IfCond = C->getCondition();
4502
4503 // Check if we have any device clause associated with the directive.
4504 const Expr *Device = nullptr;
4505 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4506 Device = C->getDevice();
4507
Alexey Bataev475a7442018-01-12 19:39:11 +00004508 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004509 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004510}
4511
Samuel Antao72590762016-01-19 20:04:50 +00004512void CodeGenFunction::EmitOMPTargetExitDataDirective(
4513 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004514 // If we don't have target devices, don't bother emitting the data mapping
4515 // code.
4516 if (CGM.getLangOpts().OMPTargetTriples.empty())
4517 return;
4518
4519 // Check if we have any if clause associated with the directive.
4520 const Expr *IfCond = nullptr;
4521 if (auto *C = S.getSingleClause<OMPIfClause>())
4522 IfCond = C->getCondition();
4523
4524 // Check if we have any device clause associated with the directive.
4525 const Expr *Device = nullptr;
4526 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4527 Device = C->getDevice();
4528
Alexey Bataev475a7442018-01-12 19:39:11 +00004529 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004530 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004531}
4532
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004533static void emitTargetParallelRegion(CodeGenFunction &CGF,
4534 const OMPTargetParallelDirective &S,
4535 PrePostActionTy &Action) {
4536 // Get the captured statement associated with the 'parallel' region.
4537 auto *CS = S.getCapturedStmt(OMPD_parallel);
4538 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004539 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4540 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4541 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4542 CGF.EmitOMPPrivateClause(S, PrivateScope);
4543 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4544 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004545 // TODO: Add support for clauses.
4546 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004547 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004548 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004549 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4550 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004551 emitPostUpdateForReductionClause(
4552 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004553}
4554
4555void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4556 CodeGenModule &CGM, StringRef ParentName,
4557 const OMPTargetParallelDirective &S) {
4558 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4559 emitTargetParallelRegion(CGF, S, Action);
4560 };
4561 llvm::Function *Fn;
4562 llvm::Constant *Addr;
4563 // Emit target region as a standalone region.
4564 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4565 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4566 assert(Fn && Addr && "Target device function emission failed.");
4567}
4568
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004569void CodeGenFunction::EmitOMPTargetParallelDirective(
4570 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004571 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4572 emitTargetParallelRegion(CGF, S, Action);
4573 };
4574 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004575}
4576
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004577static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4578 const OMPTargetParallelForDirective &S,
4579 PrePostActionTy &Action) {
4580 Action.Enter(CGF);
4581 // Emit directive as a combined directive that consists of two implicit
4582 // directives: 'parallel' with 'for' directive.
4583 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004584 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4585 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004586 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4587 emitDispatchForLoopBounds);
4588 };
4589 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4590 emitEmptyBoundParameters);
4591}
4592
4593void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4594 CodeGenModule &CGM, StringRef ParentName,
4595 const OMPTargetParallelForDirective &S) {
4596 // Emit SPMD target parallel for region as a standalone region.
4597 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4598 emitTargetParallelForRegion(CGF, S, Action);
4599 };
4600 llvm::Function *Fn;
4601 llvm::Constant *Addr;
4602 // Emit target region as a standalone region.
4603 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4604 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4605 assert(Fn && Addr && "Target device function emission failed.");
4606}
4607
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004608void CodeGenFunction::EmitOMPTargetParallelForDirective(
4609 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004610 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4611 emitTargetParallelForRegion(CGF, S, Action);
4612 };
4613 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004614}
4615
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004616static void
4617emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4618 const OMPTargetParallelForSimdDirective &S,
4619 PrePostActionTy &Action) {
4620 Action.Enter(CGF);
4621 // Emit directive as a combined directive that consists of two implicit
4622 // directives: 'parallel' with 'for' directive.
4623 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4624 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4625 emitDispatchForLoopBounds);
4626 };
4627 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4628 emitEmptyBoundParameters);
4629}
4630
4631void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4632 CodeGenModule &CGM, StringRef ParentName,
4633 const OMPTargetParallelForSimdDirective &S) {
4634 // Emit SPMD target parallel for region as a standalone region.
4635 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4636 emitTargetParallelForSimdRegion(CGF, S, Action);
4637 };
4638 llvm::Function *Fn;
4639 llvm::Constant *Addr;
4640 // Emit target region as a standalone region.
4641 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4642 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4643 assert(Fn && Addr && "Target device function emission failed.");
4644}
4645
4646void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4647 const OMPTargetParallelForSimdDirective &S) {
4648 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4649 emitTargetParallelForSimdRegion(CGF, S, Action);
4650 };
4651 emitCommonOMPTargetDirective(*this, S, CodeGen);
4652}
4653
Alexey Bataev7292c292016-04-25 12:22:29 +00004654/// Emit a helper variable and return corresponding lvalue.
4655static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4656 const ImplicitParamDecl *PVD,
4657 CodeGenFunction::OMPPrivateScope &Privates) {
4658 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4659 Privates.addPrivate(
4660 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4661}
4662
4663void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4664 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4665 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004666 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004667 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4668 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4669 const Expr *IfCond = nullptr;
4670 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4671 if (C->getNameModifier() == OMPD_unknown ||
4672 C->getNameModifier() == OMPD_taskloop) {
4673 IfCond = C->getCondition();
4674 break;
4675 }
4676 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004677
4678 OMPTaskDataTy Data;
4679 // Check if taskloop must be emitted without taskgroup.
4680 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004681 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004682 Data.Tied = true;
4683 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004684 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4685 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004686 Data.Schedule.setInt(/*IntVal=*/false);
4687 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004688 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4689 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004690 Data.Schedule.setInt(/*IntVal=*/true);
4691 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004692 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004693
4694 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4695 // if (PreCond) {
4696 // for (IV in 0..LastIteration) BODY;
4697 // <Final counter/linear vars updates>;
4698 // }
4699 //
4700
4701 // Emit: if (PreCond) - begin.
4702 // If the condition constant folds and can be elided, avoid emitting the
4703 // whole loop.
4704 bool CondConstant;
4705 llvm::BasicBlock *ContBlock = nullptr;
4706 OMPLoopScope PreInitScope(CGF, S);
4707 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4708 if (!CondConstant)
4709 return;
4710 } else {
4711 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4712 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4713 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4714 CGF.getProfileCount(&S));
4715 CGF.EmitBlock(ThenBlock);
4716 CGF.incrementProfileCounter(&S);
4717 }
4718
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004719 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4720 CGF.EmitOMPSimdInit(S);
4721
Alexey Bataev7292c292016-04-25 12:22:29 +00004722 OMPPrivateScope LoopScope(CGF);
4723 // Emit helper vars inits.
4724 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4725 auto *I = CS->getCapturedDecl()->param_begin();
4726 auto *LBP = std::next(I, LowerBound);
4727 auto *UBP = std::next(I, UpperBound);
4728 auto *STP = std::next(I, Stride);
4729 auto *LIP = std::next(I, LastIter);
4730 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4731 LoopScope);
4732 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4733 LoopScope);
4734 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4735 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4736 LoopScope);
4737 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004738 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004739 (void)LoopScope.Privatize();
4740 // Emit the loop iteration variable.
4741 const Expr *IVExpr = S.getIterationVariable();
4742 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4743 CGF.EmitVarDecl(*IVDecl);
4744 CGF.EmitIgnoredExpr(S.getInit());
4745
4746 // Emit the iterations count variable.
4747 // If it is not a variable, Sema decided to calculate iterations count on
4748 // each iteration (e.g., it is foldable into a constant).
4749 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4750 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4751 // Emit calculation of the iterations count.
4752 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4753 }
4754
4755 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4756 S.getInc(),
4757 [&S](CodeGenFunction &CGF) {
4758 CGF.EmitOMPLoopBody(S, JumpDest());
4759 CGF.EmitStopPoint(&S);
4760 },
4761 [](CodeGenFunction &) {});
4762 // Emit: if (PreCond) - end.
4763 if (ContBlock) {
4764 CGF.EmitBranch(ContBlock);
4765 CGF.EmitBlock(ContBlock, true);
4766 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004767 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4768 if (HasLastprivateClause) {
4769 CGF.EmitOMPLastprivateClauseFinal(
4770 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4771 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4772 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4773 (*LIP)->getType(), S.getLocStart())));
4774 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004775 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004776 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4777 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4778 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004779 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4780 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004781 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4782 OutlinedFn, SharedsTy,
4783 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004784 };
4785 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4786 CodeGen);
4787 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004788 if (Data.Nogroup) {
4789 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4790 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004791 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4792 *this,
4793 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4794 PrePostActionTy &Action) {
4795 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004796 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4797 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004798 },
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 Bataev475a7442018-01-12 19:39:11 +00004830 OMPLexicalScope Scope(*this, S, OMPD_task);
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 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004852 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004853 }
4854 };
4855 OMPSimdLexicalScope Scope(*this, D);
4856 CGM.getOpenMPRuntime().emitInlinedDirective(
4857 *this,
4858 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4859 : D.getDirectiveKind(),
4860 CodeGen);
4861}