blob: 044e819543365a9c626fb5185d3fc5e044c1f42d [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
69 for (auto &C : CS->captures()) {
70 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
75 const_cast<VarDecl *>(VD),
76 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000078 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000079 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80 return CGF.EmitLValue(&DRE).getAddress();
81 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000123 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
126 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
127 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
128 });
129 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000130 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000131 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
132 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
133 for (const auto *I : PreInits->decls())
134 CGF.EmitVarDecl(cast<VarDecl>(*I));
135 }
136 }
137 }
138
139public:
140 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
141 : CodeGenFunction::RunCleanupsScope(CGF) {
142 emitPreInitStmt(CGF, S);
143 }
144};
145
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000146class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
147 CodeGenFunction::OMPPrivateScope InlinedShareds;
148
149 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
150 return CGF.LambdaCaptureFields.lookup(VD) ||
151 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
152 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
153 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
154 }
155
156public:
157 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
159 InlinedShareds(CGF) {
160 for (const auto *C : S.clauses()) {
161 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
162 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
163 for (const auto *I : PreInit->decls()) {
164 if (!I->hasAttr<OMPCaptureNoInitAttr>())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
166 else {
167 CodeGenFunction::AutoVarEmission Emission =
168 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
169 CGF.EmitAutoVarCleanups(Emission);
170 }
171 }
172 }
173 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
174 for (const Expr *E : UDP->varlists()) {
175 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
176 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
177 CGF.EmitVarDecl(*OED);
178 }
179 }
180 }
181 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
182 CGF.EmitOMPPrivateClause(S, InlinedShareds);
183 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
184 if (const Expr *E = TG->getReductionRef())
185 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
186 }
187 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
188 while (CS) {
189 for (auto &C : CS->captures()) {
190 if (C.capturesVariable() || C.capturesVariableByCopy()) {
191 auto *VD = C.getCapturedVar();
192 assert(VD == VD->getCanonicalDecl() &&
193 "Canonical decl must be captured.");
194 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
195 isCapturedVar(CGF, VD) ||
196 (CGF.CapturedStmtInfo &&
197 InlinedShareds.isGlobalVarCaptured(VD)),
198 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000199 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000200 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
201 return CGF.EmitLValue(&DRE).getAddress();
202 });
203 }
204 }
205 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
206 }
207 (void)InlinedShareds.Privatize();
208 }
209};
210
Alexey Bataev3392d762016-02-16 11:18:12 +0000211} // namespace
212
Alexey Bataevf8365372017-11-17 17:57:25 +0000213static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
214 const OMPExecutableDirective &S,
215 const RegionCodeGenTy &CodeGen);
216
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000217LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
218 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
220 OrigVD = OrigVD->getCanonicalDecl();
221 bool IsCaptured =
222 LambdaCaptureFields.lookup(OrigVD) ||
223 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
224 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
226 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
227 return EmitLValue(&DRE);
228 }
229 }
230 return EmitLValue(E);
231}
232
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
234 auto &C = getContext();
235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
239 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
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()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000282 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000283 LValue SrcLV =
284 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
285
286 // Store the value using the source type pointer.
287 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
288
289 // Load the value using the destination type pointer.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000290 CV = EmitLoadOfLValue(DstLV, CurCap->getLocation()).getScalarVal();
Samuel Antao6d004262016-06-16 18:39:34 +0000291 }
292 CapturedVars.push_back(CV);
293 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000296 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 }
298}
299
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000300static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
301 QualType DstType, StringRef Name,
302 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000303 bool isReferenceType = false) {
304 ASTContext &Ctx = CGF.getContext();
305
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000306 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
307 Ctx.getUIntPtrType(),
308 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000309 auto TmpAddr =
310 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
311 .getAddress();
312
313 // If we are dealing with references we need to return the address of the
314 // reference instead of the reference of the value.
315 if (isReferenceType) {
316 QualType RefType = Ctx.getLValueReferenceType(DstType);
317 auto *RefVal = TmpAddr.getPointer();
318 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
319 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000320 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000321 }
322
323 return TmpAddr;
324}
325
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000326static QualType getCanonicalParamType(ASTContext &C, QualType T) {
327 if (T->isLValueReferenceType()) {
328 return C.getLValueReferenceType(
329 getCanonicalParamType(C, T.getNonReferenceType()),
330 /*SpelledAsLValue=*/false);
331 }
332 if (T->isPointerType())
333 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000334 if (auto *A = T->getAsArrayTypeUnsafe()) {
335 if (auto *VLA = dyn_cast<VariableArrayType>(A))
336 return getCanonicalParamType(C, VLA->getElementType());
337 else if (!A->isVariablyModifiedType())
338 return C.getCanonicalType(T);
339 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000340 return C.getCanonicalParamType(T);
341}
342
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343namespace {
344 /// Contains required data for proper outlined function codegen.
345 struct FunctionOptions {
346 /// Captured statement for which the function is generated.
347 const CapturedStmt *S = nullptr;
348 /// true if cast to/from UIntPtr is required for variables captured by
349 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000350 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000351 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000355 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000356 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
357 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000358 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000359 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
360 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000361 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000362 };
363}
364
Alexey Bataeve754b182017-08-09 19:38:53 +0000365static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000367 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000368 &LocalAddrs,
369 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
370 &VLASizes,
371 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
372 const CapturedDecl *CD = FO.S->getCapturedDecl();
373 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 assert(CD->hasBody() && "missing CapturedDecl body");
375
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000378 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000380 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000381 Args.append(CD->param_begin(),
382 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000383 TargetArgs.append(
384 CD->param_begin(),
385 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000387 FunctionDecl *DebugFunctionDecl = nullptr;
388 if (!FO.UIntPtrCastRequired) {
389 FunctionProtoType::ExtProtoInfo EPI;
390 DebugFunctionDecl = FunctionDecl::Create(
391 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
392 SourceLocation(), DeclarationName(), Ctx.VoidTy,
393 Ctx.getTrivialTypeSourceInfo(
394 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
395 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
396 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 for (auto *FD : RD->fields()) {
398 QualType ArgType = FD->getType();
399 IdentifierInfo *II = nullptr;
400 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000401
402 // If this is a capture by copy and the type is not a pointer, the outlined
403 // function argument type should be uintptr and the value properly casted to
404 // uintptr. This is necessary given that the runtime library is only able to
405 // deal with pointers. We can pass in the same way the VLA type sizes to the
406 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000407 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000409 if (FO.UIntPtrCastRequired)
410 ArgType = Ctx.getUIntPtrType();
411 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000412
413 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000414 CapVar = I->getCapturedVar();
415 II = CapVar->getIdentifier();
416 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 else {
419 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000420 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000421 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000422 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000423 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000424 VarDecl *Arg;
425 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
426 Arg = ParmVarDecl::Create(
427 Ctx, DebugFunctionDecl,
428 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
429 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
430 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
431 } else {
432 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
433 II, ArgType, ImplicitParamDecl::Other);
434 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000435 Args.emplace_back(Arg);
436 // Do not cast arguments if we emit function with non-original types.
437 TargetArgs.emplace_back(
438 FO.UIntPtrCastRequired
439 ? Arg
440 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 ++I;
442 }
443 Args.append(
444 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
445 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000446 TargetArgs.append(
447 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
448 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449
450 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000451 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000453 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
454
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000455 llvm::Function *F =
456 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
457 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
459 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000460 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000461
462 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000463 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
464 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000466 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000467 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000468 // Do not map arguments if we emit function with non-original types.
469 Address LocalAddr(Address::invalid());
470 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
471 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
472 TargetArgs[Cnt]);
473 } else {
474 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
475 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000476 // If we are capturing a pointer by copy we don't need to do anything, just
477 // use the value that we get from the arguments.
478 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000479 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000480 // If the variable is a reference we need to materialize it here.
481 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000482 Address RefAddr = CGF.CreateMemTemp(
483 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
484 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
485 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000486 LocalAddr = RefAddr;
487 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000488 if (!FO.RegisterCastedArgsOnly)
489 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000490 ++Cnt;
491 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000492 continue;
493 }
494
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000495 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
496 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000497 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000499 ArgLVal = CGF.MakeAddrLValue(
500 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
501 Args[Cnt]->getName(), ArgLVal),
502 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000503 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000504 auto *ExprArg =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000505 CGF.EmitLoadOfLValue(ArgLVal, I->getLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000506 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000507 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000508 } else if (I->capturesVariable()) {
509 auto *Var = I->getCapturedVar();
510 QualType VarTy = Var->getType();
511 Address ArgAddr = ArgLVal.getAddress();
512 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000513 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000514 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000515 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000516 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000517 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000518 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
519 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000520 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000521 if (!FO.RegisterCastedArgsOnly) {
522 LocalAddrs.insert(
523 {Args[Cnt],
524 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
525 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000526 } else if (I->capturesVariableByCopy()) {
527 assert(!FD->getType()->isAnyPointerType() &&
528 "Not expecting a captured pointer.");
529 auto *Var = I->getCapturedVar();
530 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000531 LocalAddrs.insert(
532 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000533 {Var, FO.UIntPtrCastRequired
534 ? castValueFromUintptr(CGF, I->getLocation(),
535 FD->getType(), Args[Cnt]->getName(),
536 ArgLVal, VarTy->isReferenceType())
537 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000538 } else {
539 // If 'this' is captured, load it into CXXThisValue.
540 assert(I->capturesThis());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000541 CXXThisValue =
542 CGF.EmitLoadOfLValue(ArgLVal, I->getLocation()).getScalarVal();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000543 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000544 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000545 ++Cnt;
546 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000547 }
548
Alexey Bataeve754b182017-08-09 19:38:53 +0000549 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000550}
551
552llvm::Function *
553CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
554 assert(
555 CapturedStmtInfo &&
556 "CapturedStmtInfo should be set when generating the captured function");
557 const CapturedDecl *CD = S.getCapturedDecl();
558 // Build the argument list.
559 bool NeedWrapperFunction =
560 getDebugInfo() &&
561 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
562 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000563 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000564 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000565 SmallString<256> Buffer;
566 llvm::raw_svector_ostream Out(Buffer);
567 Out << CapturedStmtInfo->getHelperName();
568 if (NeedWrapperFunction)
569 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000570 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000571 Out.str());
572 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
573 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000574 for (const auto &LocalAddrPair : LocalAddrs) {
575 if (LocalAddrPair.second.first) {
576 setAddrOfLocalVar(LocalAddrPair.second.first,
577 LocalAddrPair.second.second);
578 }
579 }
580 for (const auto &VLASizePair : VLASizes)
581 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000582 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000583 CapturedStmtInfo->EmitBody(*this, CD->getBody());
584 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000585 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000586 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000587
Alexey Bataevefd884d2017-08-04 21:26:25 +0000588 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000589 /*RegisterCastedArgsOnly=*/true,
590 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000591 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000592 Args.clear();
593 LocalAddrs.clear();
594 VLASizes.clear();
595 llvm::Function *WrapperF =
596 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000597 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000598 llvm::SmallVector<llvm::Value *, 4> CallArgs;
599 for (const auto *Arg : Args) {
600 llvm::Value *CallArg;
601 auto I = LocalAddrs.find(Arg);
602 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000603 LValue LV = WrapperCGF.MakeAddrLValue(
604 I->second.second,
605 I->second.first ? I->second.first->getType() : Arg->getType(),
606 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000607 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000608 } else {
609 auto EI = VLASizes.find(Arg);
610 if (EI != VLASizes.end())
611 CallArg = EI->second.second;
612 else {
613 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000614 Arg->getType(),
615 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000616 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 }
618 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000619 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000621 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
622 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000623 WrapperCGF.FinishFunction();
624 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000625}
626
Alexey Bataev9959db52014-05-06 10:08:46 +0000627//===----------------------------------------------------------------------===//
628// OpenMP Directive Emission
629//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000631 Address DestAddr, Address SrcAddr, QualType OriginalType,
632 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000633 // Perform element-by-element initialization.
634 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000635
636 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000637 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000638 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
639 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
640
641 auto SrcBegin = SrcAddr.getPointer();
642 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000644 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
645 // The basic structure here is a while-do loop.
646 auto BodyBB = createBasicBlock("omp.arraycpy.body");
647 auto DoneBB = createBasicBlock("omp.arraycpy.done");
648 auto IsEmpty =
649 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
650 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000651
Alexey Bataev420d45b2015-04-14 05:11:24 +0000652 // Enter the loop body, making that address the current address.
653 auto EntryBB = Builder.GetInsertBlock();
654 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000655
656 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
657
658 llvm::PHINode *SrcElementPHI =
659 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
660 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
661 Address SrcElementCurrent =
662 Address(SrcElementPHI,
663 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
664
665 llvm::PHINode *DestElementPHI =
666 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
667 DestElementPHI->addIncoming(DestBegin, EntryBB);
668 Address DestElementCurrent =
669 Address(DestElementPHI,
670 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000671
Alexey Bataev420d45b2015-04-14 05:11:24 +0000672 // Emit copy.
673 CopyGen(DestElementCurrent, SrcElementCurrent);
674
675 // Shift the address forward by one element.
676 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000677 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000678 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000679 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000680 // Check whether we've reached the end.
681 auto Done =
682 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
683 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000684 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
685 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000686
687 // Done.
688 EmitBlock(DoneBB, /*IsFinished=*/true);
689}
690
John McCall7f416cc2015-09-08 08:05:57 +0000691void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
692 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000693 const VarDecl *SrcVD, const Expr *Copy) {
694 if (OriginalType->isArrayType()) {
695 auto *BO = dyn_cast<BinaryOperator>(Copy);
696 if (BO && BO->getOpcode() == BO_Assign) {
697 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000698 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000699 } else {
700 // For arrays with complex element types perform element by element
701 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000702 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000703 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000704 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 // Working with the single array element, so have to remap
706 // destination and source variables to corresponding array
707 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000708 CodeGenFunction::OMPPrivateScope Remap(*this);
709 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 return DestElement;
711 });
712 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000713 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000715 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000718 } else {
719 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000720 CodeGenFunction::OMPPrivateScope Remap(*this);
721 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
722 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000723 (void)Remap.Privatize();
724 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000725 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000727}
728
Alexey Bataev69c62a92015-04-15 04:52:20 +0000729bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
730 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000731 if (!HaveInsertPoint())
732 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000733 bool FirstprivateIsLastprivate = false;
734 llvm::DenseSet<const VarDecl *> Lastprivates;
735 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
736 for (const auto *D : C->varlists())
737 Lastprivates.insert(
738 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
739 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000740 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000741 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
742 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
743 // Force emission of the firstprivate copy if the directive does not emit
744 // outlined function, like omp for, omp simd, omp distribute etc.
745 bool MustEmitFirstprivateCopy =
746 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000747 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000748 auto IRef = C->varlist_begin();
749 auto InitsRef = C->inits().begin();
750 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000751 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752 bool ThisFirstprivateIsLastprivate =
753 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
754 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000755 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000756 !FD->getType()->isReferenceType()) {
757 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
758 ++IRef;
759 ++InitsRef;
760 continue;
761 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000762 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000763 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000764 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000765 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
766 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
767 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000768 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
769 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
770 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000771 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000772 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000773 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000774 // Emit VarDecl with copy init for arrays.
775 // Get the address of the original variable captured in current
776 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000777 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000778 auto Emission = EmitAutoVarAlloca(*VD);
779 auto *Init = VD->getInit();
780 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
781 // Perform simple memcpy.
782 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000783 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000784 } else {
785 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000786 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000787 [this, VDInit, Init](Address DestElement,
788 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000789 // Clean up any temporaries needed by the initialization.
790 RunCleanupsScope InitScope(*this);
791 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000792 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000793 EmitAnyExprToMem(Init, DestElement,
794 Init->getType().getQualifiers(),
795 /*IsInitializer*/ false);
796 LocalDeclMap.erase(VDInit);
797 });
798 }
799 EmitAutoVarCleanups(Emission);
800 return Emission.getAllocatedAddress();
801 });
802 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000803 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000804 // Emit private VarDecl with copy init.
805 // Remap temp VDInit variable to the address of the original
806 // variable
807 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000808 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000809 EmitDecl(*VD);
810 LocalDeclMap.erase(VDInit);
811 return GetAddrOfLocalVar(VD);
812 });
813 }
814 assert(IsRegistered &&
815 "firstprivate var already registered as private");
816 // Silence the warning about unused variable.
817 (void)IsRegistered;
818 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000819 ++IRef;
820 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000821 }
822 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000823 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000824}
825
Alexey Bataev03b340a2014-10-21 03:16:40 +0000826void CodeGenFunction::EmitOMPPrivateClause(
827 const OMPExecutableDirective &D,
828 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000829 if (!HaveInsertPoint())
830 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000831 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000832 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000833 auto IRef = C->varlist_begin();
834 for (auto IInit : C->private_copies()) {
835 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000836 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
837 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
838 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000839 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000840 // Emit private VarDecl with copy init.
841 EmitDecl(*VD);
842 return GetAddrOfLocalVar(VD);
843 });
844 assert(IsRegistered && "private var already registered as private");
845 // Silence the warning about unused variable.
846 (void)IsRegistered;
847 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000848 ++IRef;
849 }
850 }
851}
852
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000853bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000854 if (!HaveInsertPoint())
855 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000856 // threadprivate_var1 = master_threadprivate_var1;
857 // operator=(threadprivate_var2, master_threadprivate_var2);
858 // ...
859 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000860 llvm::DenseSet<const VarDecl *> CopiedVars;
861 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000862 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000863 auto IRef = C->varlist_begin();
864 auto ISrcRef = C->source_exprs().begin();
865 auto IDestRef = C->destination_exprs().begin();
866 for (auto *AssignOp : C->assignment_ops()) {
867 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000868 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000869 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000870 // Get the address of the master variable. If we are emitting code with
871 // TLS support, the address is passed from the master as field in the
872 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000873 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000874 if (getLangOpts().OpenMPUseTLS &&
875 getContext().getTargetInfo().isTLSSupported()) {
876 assert(CapturedStmtInfo->lookup(VD) &&
877 "Copyin threadprivates should have been captured!");
878 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
879 VK_LValue, (*IRef)->getExprLoc());
880 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000881 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000882 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000883 MasterAddr =
884 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
885 : CGM.GetAddrOfGlobal(VD),
886 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000887 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000888 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000889 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000890 if (CopiedVars.size() == 1) {
891 // At first check if current thread is a master thread. If it is, no
892 // need to copy data.
893 CopyBegin = createBasicBlock("copyin.not.master");
894 CopyEnd = createBasicBlock("copyin.not.master.end");
895 Builder.CreateCondBr(
896 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000897 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
898 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000899 CopyBegin, CopyEnd);
900 EmitBlock(CopyBegin);
901 }
902 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
903 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000904 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000905 }
906 ++IRef;
907 ++ISrcRef;
908 ++IDestRef;
909 }
910 }
911 if (CopyEnd) {
912 // Exit out of copying procedure for non-master thread.
913 EmitBlock(CopyEnd, /*IsFinished=*/true);
914 return true;
915 }
916 return false;
917}
918
Alexey Bataev38e89532015-04-16 04:54:05 +0000919bool CodeGenFunction::EmitOMPLastprivateClauseInit(
920 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000921 if (!HaveInsertPoint())
922 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000923 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000924 llvm::DenseSet<const VarDecl *> SIMDLCVs;
925 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
926 auto *LoopDirective = cast<OMPLoopDirective>(&D);
927 for (auto *C : LoopDirective->counters()) {
928 SIMDLCVs.insert(
929 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
930 }
931 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000932 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000933 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000934 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000935 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
936 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000937 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000938 auto IRef = C->varlist_begin();
939 auto IDestRef = C->destination_exprs().begin();
940 for (auto *IInit : C->private_copies()) {
941 // Keep the address of the original variable for future update at the end
942 // of the loop.
943 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000944 // Taskloops do not require additional initialization, it is done in
945 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000946 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
947 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000948 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000949 DeclRefExpr DRE(
950 const_cast<VarDecl *>(OrigVD),
951 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
952 OrigVD) != nullptr,
953 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
954 return EmitLValue(&DRE).getAddress();
955 });
956 // Check if the variable is also a firstprivate: in this case IInit is
957 // not generated. Initialization of this variable will happen in codegen
958 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000959 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000960 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000961 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
962 // Emit private VarDecl with copy init.
963 EmitDecl(*VD);
964 return GetAddrOfLocalVar(VD);
965 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000966 assert(IsRegistered &&
967 "lastprivate var already registered as private");
968 (void)IsRegistered;
969 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000970 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000971 ++IRef;
972 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 }
974 }
975 return HasAtLeastOneLastprivate;
976}
977
978void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000979 const OMPExecutableDirective &D, bool NoFinals,
980 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000981 if (!HaveInsertPoint())
982 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000983 // Emit following code:
984 // if (<IsLastIterCond>) {
985 // orig_var1 = private_orig_var1;
986 // ...
987 // orig_varn = private_orig_varn;
988 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000989 llvm::BasicBlock *ThenBB = nullptr;
990 llvm::BasicBlock *DoneBB = nullptr;
991 if (IsLastIterCond) {
992 ThenBB = createBasicBlock(".omp.lastprivate.then");
993 DoneBB = createBasicBlock(".omp.lastprivate.done");
994 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
995 EmitBlock(ThenBB);
996 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000997 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
998 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000999 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001000 auto IC = LoopDirective->counters().begin();
1001 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001002 auto *D =
1003 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1004 if (NoFinals)
1005 AlreadyEmittedVars.insert(D);
1006 else
1007 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001008 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001009 }
1010 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001011 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1012 auto IRef = C->varlist_begin();
1013 auto ISrcRef = C->source_exprs().begin();
1014 auto IDestRef = C->destination_exprs().begin();
1015 for (auto *AssignOp : C->assignment_ops()) {
1016 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1017 QualType Type = PrivateVD->getType();
1018 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1019 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1020 // If lastprivate variable is a loop control variable for loop-based
1021 // directive, update its value before copyin back to original
1022 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001023 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1024 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001025 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1026 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1027 // Get the address of the original variable.
1028 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1029 // Get the address of the private variable.
1030 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1031 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1032 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001033 Address(Builder.CreateLoad(PrivateAddr),
1034 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001035 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001036 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001037 ++IRef;
1038 ++ISrcRef;
1039 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001040 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001041 if (auto *PostUpdate = C->getPostUpdateExpr())
1042 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001043 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001044 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001045 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001046}
1047
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001048void CodeGenFunction::EmitOMPReductionClauseInit(
1049 const OMPExecutableDirective &D,
1050 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001051 if (!HaveInsertPoint())
1052 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001053 SmallVector<const Expr *, 4> Shareds;
1054 SmallVector<const Expr *, 4> Privates;
1055 SmallVector<const Expr *, 4> ReductionOps;
1056 SmallVector<const Expr *, 4> LHSs;
1057 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001058 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001059 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001060 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 auto ILHS = C->lhs_exprs().begin();
1062 auto IRHS = C->rhs_exprs().begin();
1063 for (const auto *Ref : C->varlists()) {
1064 Shareds.emplace_back(Ref);
1065 Privates.emplace_back(*IPriv);
1066 ReductionOps.emplace_back(*IRed);
1067 LHSs.emplace_back(*ILHS);
1068 RHSs.emplace_back(*IRHS);
1069 std::advance(IPriv, 1);
1070 std::advance(IRed, 1);
1071 std::advance(ILHS, 1);
1072 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001073 }
1074 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001075 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1076 unsigned Count = 0;
1077 auto ILHS = LHSs.begin();
1078 auto IRHS = RHSs.begin();
1079 auto IPriv = Privates.begin();
1080 for (const auto *IRef : Shareds) {
1081 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1082 // Emit private VarDecl with reduction init.
1083 RedCG.emitSharedLValue(*this, Count);
1084 RedCG.emitAggregateType(*this, Count);
1085 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1086 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1087 RedCG.getSharedLValue(Count),
1088 [&Emission](CodeGenFunction &CGF) {
1089 CGF.EmitAutoVarInit(Emission);
1090 return true;
1091 });
1092 EmitAutoVarCleanups(Emission);
1093 Address BaseAddr = RedCG.adjustPrivateAddress(
1094 *this, Count, Emission.getAllocatedAddress());
1095 bool IsRegistered = PrivateScope.addPrivate(
1096 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1097 assert(IsRegistered && "private var already registered as private");
1098 // Silence the warning about unused variable.
1099 (void)IsRegistered;
1100
1101 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1102 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001103 QualType Type = PrivateVD->getType();
1104 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1105 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001106 // Store the address of the original variable associated with the LHS
1107 // implicit variable.
1108 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1109 return RedCG.getSharedLValue(Count).getAddress();
1110 });
1111 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1112 return GetAddrOfLocalVar(PrivateVD);
1113 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001114 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1115 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 // Store the address of the original variable associated with the LHS
1117 // implicit variable.
1118 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1119 return RedCG.getSharedLValue(Count).getAddress();
1120 });
1121 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1122 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1123 ConvertTypeForMem(RHSVD->getType()),
1124 "rhs.begin");
1125 });
1126 } else {
1127 QualType Type = PrivateVD->getType();
1128 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1129 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1130 // Store the address of the original variable associated with the LHS
1131 // implicit variable.
1132 if (IsArray) {
1133 OriginalAddr = Builder.CreateElementBitCast(
1134 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1135 }
1136 PrivateScope.addPrivate(
1137 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1138 PrivateScope.addPrivate(
1139 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1140 return IsArray
1141 ? Builder.CreateElementBitCast(
1142 GetAddrOfLocalVar(PrivateVD),
1143 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1144 : GetAddrOfLocalVar(PrivateVD);
1145 });
1146 }
1147 ++ILHS;
1148 ++IRHS;
1149 ++IPriv;
1150 ++Count;
1151 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001152}
1153
1154void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001155 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001156 if (!HaveInsertPoint())
1157 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001158 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001159 llvm::SmallVector<const Expr *, 8> LHSExprs;
1160 llvm::SmallVector<const Expr *, 8> RHSExprs;
1161 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001162 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001163 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001165 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001166 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1167 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1168 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1169 }
1170 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001171 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1172 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001173 ReductionKind == OMPD_simd;
1174 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001175 // Emit nowait reduction if nowait clause is present or directive is a
1176 // parallel directive (it always has implicit barrier).
1177 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001178 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001179 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001180 }
1181}
1182
Alexey Bataev61205072016-03-02 04:57:40 +00001183static void emitPostUpdateForReductionClause(
1184 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1185 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1186 if (!CGF.HaveInsertPoint())
1187 return;
1188 llvm::BasicBlock *DoneBB = nullptr;
1189 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1190 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1191 if (!DoneBB) {
1192 if (auto *Cond = CondGen(CGF)) {
1193 // If the first post-update expression is found, emit conditional
1194 // block if it was requested.
1195 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1196 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1197 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1198 CGF.EmitBlock(ThenBB);
1199 }
1200 }
1201 CGF.EmitIgnoredExpr(PostUpdate);
1202 }
1203 }
1204 if (DoneBB)
1205 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1206}
1207
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001208namespace {
1209/// Codegen lambda for appending distribute lower and upper bounds to outlined
1210/// parallel function. This is necessary for combined constructs such as
1211/// 'distribute parallel for'
1212typedef llvm::function_ref<void(CodeGenFunction &,
1213 const OMPExecutableDirective &,
1214 llvm::SmallVectorImpl<llvm::Value *> &)>
1215 CodeGenBoundParametersTy;
1216} // anonymous namespace
1217
1218static void emitCommonOMPParallelDirective(
1219 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1220 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1221 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001222 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1223 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1224 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001225 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001226 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001227 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1228 /*IgnoreResultAssign*/ true);
1229 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1230 CGF, NumThreads, NumThreadsClause->getLocStart());
1231 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001232 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001233 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001234 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1235 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1236 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001237 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001238 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1239 if (C->getNameModifier() == OMPD_unknown ||
1240 C->getNameModifier() == OMPD_parallel) {
1241 IfCond = C->getCondition();
1242 break;
1243 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001244 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001245
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001246 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001247 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001248 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1249 // lower and upper bounds with the pragma 'for' chunking mechanism.
1250 // The following lambda takes care of appending the lower and upper bound
1251 // parameters when necessary
1252 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001253 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001254 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001255 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001256}
1257
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001258static void emitEmptyBoundParameters(CodeGenFunction &,
1259 const OMPExecutableDirective &,
1260 llvm::SmallVectorImpl<llvm::Value *> &) {}
1261
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001262void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001264 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001266 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001267 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1268 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001269 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001270 // propagation master's thread values of threadprivate variables to local
1271 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001272 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1273 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1274 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001275 }
1276 CGF.EmitOMPPrivateClause(S, PrivateScope);
1277 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1278 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001279 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001280 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001281 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001282 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1283 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001284 emitPostUpdateForReductionClause(
1285 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001286}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001287
Alexey Bataev0f34da12015-07-02 04:17:07 +00001288void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1289 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001290 RunCleanupsScope BodyScope(*this);
1291 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001292 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001293 EmitIgnoredExpr(I);
1294 }
Alexander Musman3276a272015-03-21 10:12:56 +00001295 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001296 // In distribute directives only loop counters may be marked as linear, no
1297 // need to generate the code for them.
1298 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1299 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1300 for (auto *U : C->updates())
1301 EmitIgnoredExpr(U);
1302 }
Alexander Musman3276a272015-03-21 10:12:56 +00001303 }
1304
Alexander Musmana5f070a2014-10-01 06:03:56 +00001305 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001306 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001307 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001308 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001310 // The end (updates/cleanups).
1311 EmitBlock(Continue.getBlock());
1312 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001313}
1314
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315void CodeGenFunction::EmitOMPInnerLoop(
1316 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1317 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001318 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1319 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001320 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001321
1322 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001323 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001324 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001325 const SourceRange &R = S.getSourceRange();
1326 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1327 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001328
1329 // If there are any cleanups between here and the loop-exit scope,
1330 // create a block to stage a loop exit along.
1331 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001332 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001333 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001334
Alexander Musmand196ef22014-10-07 08:57:09 +00001335 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336
Alexey Bataev2df54a02015-03-12 08:53:29 +00001337 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001338 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001339 if (ExitBlock != LoopExit.getBlock()) {
1340 EmitBlock(ExitBlock);
1341 EmitBranchThroughCleanup(LoopExit);
1342 }
1343
1344 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001345 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001346
1347 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001348 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001349 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1350
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001352
1353 // Emit "IV = IV + 1" and a back-edge to the condition block.
1354 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001355 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001356 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001357 BreakContinueStack.pop_back();
1358 EmitBranch(CondBlock);
1359 LoopStack.pop();
1360 // Emit the fall-through block.
1361 EmitBlock(LoopExit.getBlock());
1362}
1363
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001364bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001365 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001366 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001367 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001368 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001369 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001370 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001371 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001372 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001373 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1374 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1375 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1376 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1377 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1378 VD->getInit()->getType(), VK_LValue,
1379 VD->getInit()->getExprLoc());
1380 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1381 VD->getType()),
1382 /*capturedByInit=*/false);
1383 EmitAutoVarCleanups(Emission);
1384 } else
1385 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001386 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001387 // Emit the linear steps for the linear clauses.
1388 // If a step is not constant, it is pre-calculated before the loop.
1389 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1390 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001391 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001392 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001393 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001394 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001395 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001396 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001397}
1398
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001399void CodeGenFunction::EmitOMPLinearClauseFinal(
1400 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001401 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001402 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001403 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001404 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001405 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001406 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001407 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001408 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001409 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001411 // If the first post-update expression is found, emit conditional
1412 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001413 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1414 DoneBB = createBasicBlock(".omp.linear.pu.done");
1415 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1416 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001417 }
1418 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001419 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1420 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001421 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001422 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001423 Address OrigAddr = EmitLValue(&DRE).getAddress();
1424 CodeGenFunction::OMPPrivateScope VarScope(*this);
1425 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001426 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001427 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001428 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001429 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001430 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001431 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001432 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001433 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001434 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001435}
1436
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001437static void emitAlignedClause(CodeGenFunction &CGF,
1438 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001439 if (!CGF.HaveInsertPoint())
1440 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001441 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001442 unsigned ClauseAlignment = 0;
1443 if (auto AlignmentExpr = Clause->getAlignment()) {
1444 auto AlignmentCI =
1445 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1446 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001447 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001448 for (auto E : Clause->varlists()) {
1449 unsigned Alignment = ClauseAlignment;
1450 if (Alignment == 0) {
1451 // OpenMP [2.8.1, Description]
1452 // If no optional parameter is specified, implementation-defined default
1453 // alignments for SIMD instructions on the target platforms are assumed.
1454 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001455 CGF.getContext()
1456 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1457 E->getType()->getPointeeType()))
1458 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001459 }
1460 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1461 "alignment is not power of 2");
1462 if (Alignment != 0) {
1463 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1464 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1465 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001466 }
1467 }
1468}
1469
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001470void CodeGenFunction::EmitOMPPrivateLoopCounters(
1471 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1472 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001473 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001474 auto I = S.private_counters().begin();
1475 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001476 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1477 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001479 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001480 if (!LocalDeclMap.count(PrivateVD)) {
1481 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1482 EmitAutoVarCleanups(VarEmission);
1483 }
1484 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1485 /*RefersToEnclosingVariableOrCapture=*/false,
1486 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1487 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001488 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001489 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1490 VD->hasGlobalStorage()) {
1491 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1492 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1493 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1494 E->getType(), VK_LValue, E->getExprLoc());
1495 return EmitLValue(&DRE).getAddress();
1496 });
1497 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001498 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001499 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001500}
1501
Alexey Bataev62dbb972015-04-22 11:59:37 +00001502static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1503 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1504 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001505 if (!CGF.HaveInsertPoint())
1506 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001507 {
1508 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001509 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001510 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001511 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001512 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001513 CGF.EmitIgnoredExpr(I);
1514 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001515 }
1516 // Check that loop is executed at least one time.
1517 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1518}
1519
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001520void CodeGenFunction::EmitOMPLinearClause(
1521 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1522 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001523 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001524 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1525 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1526 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1527 for (auto *C : LoopDirective->counters()) {
1528 SIMDLCVs.insert(
1529 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1530 }
1531 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001532 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001533 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001534 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1536 auto *PrivateVD =
1537 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001538 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1539 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1540 // Emit private VarDecl with copy init.
1541 EmitVarDecl(*PrivateVD);
1542 return GetAddrOfLocalVar(PrivateVD);
1543 });
1544 assert(IsRegistered && "linear var already registered as private");
1545 // Silence the warning about unused variable.
1546 (void)IsRegistered;
1547 } else
1548 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001549 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001550 }
1551 }
1552}
1553
Alexey Bataev45bfad52015-08-21 12:19:04 +00001554static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001555 const OMPExecutableDirective &D,
1556 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001557 if (!CGF.HaveInsertPoint())
1558 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001559 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001560 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1561 /*ignoreResult=*/true);
1562 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1563 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1564 // In presence of finite 'safelen', it may be unsafe to mark all
1565 // the memory instructions parallel, because loop-carried
1566 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001567 if (!IsMonotonic)
1568 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001569 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001570 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1571 /*ignoreResult=*/true);
1572 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001573 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001574 // In presence of finite 'safelen', it may be unsafe to mark all
1575 // the memory instructions parallel, because loop-carried
1576 // dependences of 'safelen' iterations are possible.
1577 CGF.LoopStack.setParallel(false);
1578 }
1579}
1580
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001581void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1582 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001583 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001584 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001585 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001586 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001587}
1588
Alexey Bataevef549a82016-03-09 09:49:09 +00001589void CodeGenFunction::EmitOMPSimdFinal(
1590 const OMPLoopDirective &D,
1591 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001592 if (!HaveInsertPoint())
1593 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001594 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001595 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001596 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001597 for (auto F : D.finals()) {
1598 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001599 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1600 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1601 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1602 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001603 if (!DoneBB) {
1604 if (auto *Cond = CondGen(*this)) {
1605 // If the first post-update expression is found, emit conditional
1606 // block if it was requested.
1607 auto *ThenBB = createBasicBlock(".omp.final.then");
1608 DoneBB = createBasicBlock(".omp.final.done");
1609 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1610 EmitBlock(ThenBB);
1611 }
1612 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001613 Address OrigAddr = Address::invalid();
1614 if (CED)
1615 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1616 else {
1617 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1618 /*RefersToEnclosingVariableOrCapture=*/false,
1619 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1620 OrigAddr = EmitLValue(&DRE).getAddress();
1621 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001622 OMPPrivateScope VarScope(*this);
1623 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001624 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001625 (void)VarScope.Privatize();
1626 EmitIgnoredExpr(F);
1627 }
1628 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001629 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001630 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001631 if (DoneBB)
1632 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001633}
1634
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001635static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1636 const OMPLoopDirective &S,
1637 CodeGenFunction::JumpDest LoopExit) {
1638 CGF.EmitOMPLoopBody(S, LoopExit);
1639 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001640}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001641
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001642/// Emit a helper variable and return corresponding lvalue.
1643static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1644 const DeclRefExpr *Helper) {
1645 auto VDecl = cast<VarDecl>(Helper->getDecl());
1646 CGF.EmitVarDecl(*VDecl);
1647 return CGF.EmitLValue(Helper);
1648}
1649
Alexey Bataevf8365372017-11-17 17:57:25 +00001650static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1651 PrePostActionTy &Action) {
1652 Action.Enter(CGF);
1653 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1654 "Expected simd directive");
1655 OMPLoopScope PreInitScope(CGF, S);
1656 // if (PreCond) {
1657 // for (IV in 0..LastIteration) BODY;
1658 // <Final counter/linear vars updates>;
1659 // }
1660 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001661 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1662 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1663 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1664 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1665 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1666 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001667
Alexey Bataevf8365372017-11-17 17:57:25 +00001668 // Emit: if (PreCond) - begin.
1669 // If the condition constant folds and can be elided, avoid emitting the
1670 // whole loop.
1671 bool CondConstant;
1672 llvm::BasicBlock *ContBlock = nullptr;
1673 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1674 if (!CondConstant)
1675 return;
1676 } else {
1677 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1678 ContBlock = CGF.createBasicBlock("simd.if.end");
1679 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1680 CGF.getProfileCount(&S));
1681 CGF.EmitBlock(ThenBlock);
1682 CGF.incrementProfileCounter(&S);
1683 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001684
Alexey Bataevf8365372017-11-17 17:57:25 +00001685 // Emit the loop iteration variable.
1686 const Expr *IVExpr = S.getIterationVariable();
1687 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1688 CGF.EmitVarDecl(*IVDecl);
1689 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001690
Alexey Bataevf8365372017-11-17 17:57:25 +00001691 // Emit the iterations count variable.
1692 // If it is not a variable, Sema decided to calculate iterations count on
1693 // each iteration (e.g., it is foldable into a constant).
1694 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1695 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1696 // Emit calculation of the iterations count.
1697 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1698 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001699
Alexey Bataevf8365372017-11-17 17:57:25 +00001700 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001701
Alexey Bataevf8365372017-11-17 17:57:25 +00001702 emitAlignedClause(CGF, S);
1703 (void)CGF.EmitOMPLinearClauseInit(S);
1704 {
1705 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1706 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1707 CGF.EmitOMPLinearClause(S, LoopScope);
1708 CGF.EmitOMPPrivateClause(S, LoopScope);
1709 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1710 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1711 (void)LoopScope.Privatize();
1712 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1713 S.getInc(),
1714 [&S](CodeGenFunction &CGF) {
1715 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1716 CGF.EmitStopPoint(&S);
1717 },
1718 [](CodeGenFunction &) {});
1719 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001720 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001721 // Emit final copy of the lastprivate variables at the end of loops.
1722 if (HasLastprivateClause)
1723 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1724 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1725 emitPostUpdateForReductionClause(
1726 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1727 }
1728 CGF.EmitOMPLinearClauseFinal(
1729 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1730 // Emit: if (PreCond) - end.
1731 if (ContBlock) {
1732 CGF.EmitBranch(ContBlock);
1733 CGF.EmitBlock(ContBlock, true);
1734 }
1735}
1736
1737void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1738 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1739 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001740 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001741 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001742 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001743}
1744
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001745void CodeGenFunction::EmitOMPOuterLoop(
1746 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1747 CodeGenFunction::OMPPrivateScope &LoopScope,
1748 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1749 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1750 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001751 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001752
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001753 const Expr *IVExpr = S.getIterationVariable();
1754 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1755 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1756
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001757 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1758
1759 // Start the loop with a block that tests the condition.
1760 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1761 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001762 const SourceRange &R = S.getSourceRange();
1763 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1764 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001765
1766 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001767 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001768 // UB = min(UB, GlobalUB) or
1769 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1770 // 'distribute parallel for')
1771 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001772 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001773 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001774 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001775 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001777 BoolCondVal =
1778 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1779 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001780 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001781
1782 // If there are any cleanups between here and the loop-exit scope,
1783 // create a block to stage a loop exit along.
1784 auto ExitBlock = LoopExit.getBlock();
1785 if (LoopScope.requiresCleanups())
1786 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1787
1788 auto LoopBody = createBasicBlock("omp.dispatch.body");
1789 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1790 if (ExitBlock != LoopExit.getBlock()) {
1791 EmitBlock(ExitBlock);
1792 EmitBranchThroughCleanup(LoopExit);
1793 }
1794 EmitBlock(LoopBody);
1795
Alexander Musman92bdaab2015-03-12 13:37:50 +00001796 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1797 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001798 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001799 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001800
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001801 // Create a block for the increment.
1802 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1803 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1804
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001805 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1806 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001807 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1808 LoopStack.setParallel(!IsMonotonic);
1809 else
1810 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001811
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001812 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001813
1814 // when 'distribute' is not combined with a 'for':
1815 // while (idx <= UB) { BODY; ++idx; }
1816 // when 'distribute' is combined with a 'for'
1817 // (e.g. 'distribute parallel for')
1818 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1819 EmitOMPInnerLoop(
1820 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1821 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1822 CodeGenLoop(CGF, S, LoopExit);
1823 },
1824 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1825 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1826 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001827
1828 EmitBlock(Continue.getBlock());
1829 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001830 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001831 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001832 EmitIgnoredExpr(LoopArgs.NextLB);
1833 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001834 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001835
1836 EmitBranch(CondBlock);
1837 LoopStack.pop();
1838 // Emit the fall-through block.
1839 EmitBlock(LoopExit.getBlock());
1840
1841 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001842 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1843 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001844 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1845 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001846 };
1847 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001848}
1849
1850void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001851 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001852 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001853 const OMPLoopArguments &LoopArgs,
1854 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001855 auto &RT = CGM.getOpenMPRuntime();
1856
1857 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001858 const bool DynamicOrOrdered =
1859 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001860
1861 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001862 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001863 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001864 "static non-chunked schedule does not need outer loop");
1865
1866 // Emit outer loop.
1867 //
1868 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1869 // When schedule(dynamic,chunk_size) is specified, the iterations are
1870 // distributed to threads in the team in chunks as the threads request them.
1871 // Each thread executes a chunk of iterations, then requests another chunk,
1872 // until no chunks remain to be distributed. Each chunk contains chunk_size
1873 // iterations, except for the last chunk to be distributed, which may have
1874 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1875 //
1876 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1877 // to threads in the team in chunks as the executing threads request them.
1878 // Each thread executes a chunk of iterations, then requests another chunk,
1879 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1880 // each chunk is proportional to the number of unassigned iterations divided
1881 // by the number of threads in the team, decreasing to 1. For a chunk_size
1882 // with value k (greater than 1), the size of each chunk is determined in the
1883 // same way, with the restriction that the chunks do not contain fewer than k
1884 // iterations (except for the last chunk to be assigned, which may have fewer
1885 // than k iterations).
1886 //
1887 // When schedule(auto) is specified, the decision regarding scheduling is
1888 // delegated to the compiler and/or runtime system. The programmer gives the
1889 // implementation the freedom to choose any possible mapping of iterations to
1890 // threads in the team.
1891 //
1892 // When schedule(runtime) is specified, the decision regarding scheduling is
1893 // deferred until run time, and the schedule and chunk size are taken from the
1894 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1895 // implementation defined
1896 //
1897 // while(__kmpc_dispatch_next(&LB, &UB)) {
1898 // idx = LB;
1899 // while (idx <= UB) { BODY; ++idx;
1900 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1901 // } // inner loop
1902 // }
1903 //
1904 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1905 // When schedule(static, chunk_size) is specified, iterations are divided into
1906 // chunks of size chunk_size, and the chunks are assigned to the threads in
1907 // the team in a round-robin fashion in the order of the thread number.
1908 //
1909 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1910 // while (idx <= UB) { BODY; ++idx; } // inner loop
1911 // LB = LB + ST;
1912 // UB = UB + ST;
1913 // }
1914 //
1915
1916 const Expr *IVExpr = S.getIterationVariable();
1917 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1918 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1919
1920 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001921 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1922 llvm::Value *LBVal = DispatchBounds.first;
1923 llvm::Value *UBVal = DispatchBounds.second;
1924 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1925 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001926 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001927 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001928 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001929 CGOpenMPRuntime::StaticRTInput StaticInit(
1930 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1931 LoopArgs.ST, LoopArgs.Chunk);
1932 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1933 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001934 }
1935
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001936 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1937 const unsigned IVSize,
1938 const bool IVSigned) {
1939 if (Ordered) {
1940 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1941 IVSigned);
1942 }
1943 };
1944
1945 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1946 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1947 OuterLoopArgs.IncExpr = S.getInc();
1948 OuterLoopArgs.Init = S.getInit();
1949 OuterLoopArgs.Cond = S.getCond();
1950 OuterLoopArgs.NextLB = S.getNextLowerBound();
1951 OuterLoopArgs.NextUB = S.getNextUpperBound();
1952 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1953 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001954}
1955
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001956static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1957 const unsigned IVSize, const bool IVSigned) {}
1958
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001959void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001960 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1961 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1962 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001963
1964 auto &RT = CGM.getOpenMPRuntime();
1965
1966 // Emit outer loop.
1967 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1968 // dynamic
1969 //
1970
1971 const Expr *IVExpr = S.getIterationVariable();
1972 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1973 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1974
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001975 CGOpenMPRuntime::StaticRTInput StaticInit(
1976 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1977 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1978 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001979
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001980 // for combined 'distribute' and 'for' the increment expression of distribute
1981 // is store in DistInc. For 'distribute' alone, it is in Inc.
1982 Expr *IncExpr;
1983 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1984 IncExpr = S.getDistInc();
1985 else
1986 IncExpr = S.getInc();
1987
1988 // this routine is shared by 'omp distribute parallel for' and
1989 // 'omp distribute': select the right EUB expression depending on the
1990 // directive
1991 OMPLoopArguments OuterLoopArgs;
1992 OuterLoopArgs.LB = LoopArgs.LB;
1993 OuterLoopArgs.UB = LoopArgs.UB;
1994 OuterLoopArgs.ST = LoopArgs.ST;
1995 OuterLoopArgs.IL = LoopArgs.IL;
1996 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1997 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1998 ? S.getCombinedEnsureUpperBound()
1999 : S.getEnsureUpperBound();
2000 OuterLoopArgs.IncExpr = IncExpr;
2001 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2002 ? S.getCombinedInit()
2003 : S.getInit();
2004 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2005 ? S.getCombinedCond()
2006 : S.getCond();
2007 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2008 ? S.getCombinedNextLowerBound()
2009 : S.getNextLowerBound();
2010 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2011 ? S.getCombinedNextUpperBound()
2012 : S.getNextUpperBound();
2013
2014 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2015 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2016 emitEmptyOrdered);
2017}
2018
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002019static std::pair<LValue, LValue>
2020emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2021 const OMPExecutableDirective &S) {
2022 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2023 LValue LB =
2024 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2025 LValue UB =
2026 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2027
2028 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2029 // parallel for') we need to use the 'distribute'
2030 // chunk lower and upper bounds rather than the whole loop iteration
2031 // space. These are parameters to the outlined function for 'parallel'
2032 // and we copy the bounds of the previous schedule into the
2033 // the current ones.
2034 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2035 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002036 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2037 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002038 PrevLBVal = CGF.EmitScalarConversion(
2039 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002040 LS.getIterationVariable()->getType(),
2041 LS.getPrevLowerBoundVariable()->getExprLoc());
2042 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2043 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002044 PrevUBVal = CGF.EmitScalarConversion(
2045 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002046 LS.getIterationVariable()->getType(),
2047 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002048
2049 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2050 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2051
2052 return {LB, UB};
2053}
2054
2055/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2056/// we need to use the LB and UB expressions generated by the worksharing
2057/// code generation support, whereas in non combined situations we would
2058/// just emit 0 and the LastIteration expression
2059/// This function is necessary due to the difference of the LB and UB
2060/// types for the RT emission routines for 'for_static_init' and
2061/// 'for_dispatch_init'
2062static std::pair<llvm::Value *, llvm::Value *>
2063emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2064 const OMPExecutableDirective &S,
2065 Address LB, Address UB) {
2066 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2067 const Expr *IVExpr = LS.getIterationVariable();
2068 // when implementing a dynamic schedule for a 'for' combined with a
2069 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2070 // is not normalized as each team only executes its own assigned
2071 // distribute chunk
2072 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002073 llvm::Value *LBVal =
2074 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2075 llvm::Value *UBVal =
2076 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002077 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002078}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002079
2080static void emitDistributeParallelForDistributeInnerBoundParams(
2081 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2082 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2083 const auto &Dir = cast<OMPLoopDirective>(S);
2084 LValue LB =
2085 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2086 auto LBCast = CGF.Builder.CreateIntCast(
2087 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2088 CapturedVars.push_back(LBCast);
2089 LValue UB =
2090 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2091
2092 auto UBCast = CGF.Builder.CreateIntCast(
2093 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2094 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002095}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002096
2097static void
2098emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2099 const OMPLoopDirective &S,
2100 CodeGenFunction::JumpDest LoopExit) {
2101 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2102 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002103 bool HasCancel = false;
2104 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2105 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2106 HasCancel = D->hasCancel();
2107 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2108 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002109 else if (const auto *D =
2110 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2111 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002112 }
2113 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2114 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002115 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2116 emitDistributeParallelForInnerBounds,
2117 emitDistributeParallelForDispatchBounds);
2118 };
2119
2120 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002121 CGF, S,
2122 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2123 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002125}
2126
Carlo Bertolli9925f152016-06-27 14:55:37 +00002127void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2128 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002129 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2130 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2131 S.getDistInc());
2132 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002133 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002134 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002135}
2136
Kelvin Li4a39add2016-07-05 05:00:15 +00002137void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2138 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002139 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2140 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2141 S.getDistInc());
2142 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002143 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002144 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002145}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002146
2147void CodeGenFunction::EmitOMPDistributeSimdDirective(
2148 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002149 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2150 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2151 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002152 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002153 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002154}
2155
Alexey Bataevf8365372017-11-17 17:57:25 +00002156void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2157 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2158 // Emit SPMD target parallel for region as a standalone region.
2159 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2160 emitOMPSimdRegion(CGF, S, Action);
2161 };
2162 llvm::Function *Fn;
2163 llvm::Constant *Addr;
2164 // Emit target region as a standalone region.
2165 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2166 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2167 assert(Fn && Addr && "Target device function emission failed.");
2168}
2169
Kelvin Li986330c2016-07-20 22:57:10 +00002170void CodeGenFunction::EmitOMPTargetSimdDirective(
2171 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002172 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2173 emitOMPSimdRegion(CGF, S, Action);
2174 };
2175 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002176}
2177
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002178namespace {
2179 struct ScheduleKindModifiersTy {
2180 OpenMPScheduleClauseKind Kind;
2181 OpenMPScheduleClauseModifier M1;
2182 OpenMPScheduleClauseModifier M2;
2183 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2184 OpenMPScheduleClauseModifier M1,
2185 OpenMPScheduleClauseModifier M2)
2186 : Kind(Kind), M1(M1), M2(M2) {}
2187 };
2188} // namespace
2189
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002190bool CodeGenFunction::EmitOMPWorksharingLoop(
2191 const OMPLoopDirective &S, Expr *EUB,
2192 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2193 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002194 // Emit the loop iteration variable.
2195 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2196 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2197 EmitVarDecl(*IVDecl);
2198
2199 // Emit the iterations count variable.
2200 // If it is not a variable, Sema decided to calculate iterations count on each
2201 // iteration (e.g., it is foldable into a constant).
2202 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2203 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2204 // Emit calculation of the iterations count.
2205 EmitIgnoredExpr(S.getCalcLastIteration());
2206 }
2207
2208 auto &RT = CGM.getOpenMPRuntime();
2209
Alexey Bataev38e89532015-04-16 04:54:05 +00002210 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002211 // Check pre-condition.
2212 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002213 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002214 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002215 // If the condition constant folds and can be elided, avoid emitting the
2216 // whole loop.
2217 bool CondConstant;
2218 llvm::BasicBlock *ContBlock = nullptr;
2219 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2220 if (!CondConstant)
2221 return false;
2222 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002223 auto *ThenBlock = createBasicBlock("omp.precond.then");
2224 ContBlock = createBasicBlock("omp.precond.end");
2225 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002226 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002227 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002228 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002229 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002230
Alexey Bataev8b427062016-05-25 12:36:08 +00002231 bool Ordered = false;
2232 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2233 if (OrderedClause->getNumForLoops())
2234 RT.emitDoacrossInit(*this, S);
2235 else
2236 Ordered = true;
2237 }
2238
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002239 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002240 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002241 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002242 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002243
2244 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2245 LValue LB = Bounds.first;
2246 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002247 LValue ST =
2248 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2249 LValue IL =
2250 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2251
Alexander Musmanc6388682014-12-15 07:07:06 +00002252 // Emit 'then' code.
2253 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002254 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002255 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002256 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002257 // initialization of firstprivate variables and post-update of
2258 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002259 CGM.getOpenMPRuntime().emitBarrierCall(
2260 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2261 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002262 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002263 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002264 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002265 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002266 EmitOMPPrivateLoopCounters(S, LoopScope);
2267 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002268 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002269
2270 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002271 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002272 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002273 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002274 ScheduleKind.Schedule = C->getScheduleKind();
2275 ScheduleKind.M1 = C->getFirstScheduleModifier();
2276 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002277 if (const auto *Ch = C->getChunkSize()) {
2278 Chunk = EmitScalarExpr(Ch);
2279 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2280 S.getIterationVariable()->getType(),
2281 S.getLocStart());
2282 }
2283 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002284 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2285 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002286 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2287 // If the static schedule kind is specified or if the ordered clause is
2288 // specified, and if no monotonic modifier is specified, the effect will
2289 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002290 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002291 /* Chunked */ Chunk != nullptr) &&
2292 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002293 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2294 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002295 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2296 // When no chunk_size is specified, the iteration space is divided into
2297 // chunks that are approximately equal in size, and at most one chunk is
2298 // distributed to each thread. Note that the size of the chunks is
2299 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002300 CGOpenMPRuntime::StaticRTInput StaticInit(
2301 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2302 UB.getAddress(), ST.getAddress());
2303 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2304 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002305 auto LoopExit =
2306 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002307 // UB = min(UB, GlobalUB);
2308 EmitIgnoredExpr(S.getEnsureUpperBound());
2309 // IV = LB;
2310 EmitIgnoredExpr(S.getInit());
2311 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002312 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2313 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002314 [&S, LoopExit](CodeGenFunction &CGF) {
2315 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002316 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002317 },
2318 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002319 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002320 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002321 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002322 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2323 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002324 };
2325 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002326 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002327 const bool IsMonotonic =
2328 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2329 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2330 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2331 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002332 // Emit the outer loop, which requests its work chunk [LB..UB] from
2333 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002334 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2335 ST.getAddress(), IL.getAddress(),
2336 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002337 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002338 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002339 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002340 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2341 EmitOMPSimdFinal(S,
2342 [&](CodeGenFunction &CGF) -> llvm::Value * {
2343 return CGF.Builder.CreateIsNotNull(
2344 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2345 });
2346 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002347 EmitOMPReductionClauseFinal(
2348 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2349 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2350 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002351 // Emit post-update of the reduction variables if IsLastIter != 0.
2352 emitPostUpdateForReductionClause(
2353 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2354 return CGF.Builder.CreateIsNotNull(
2355 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2356 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002357 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2358 if (HasLastprivateClause)
2359 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002360 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2361 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002362 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002363 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002364 return CGF.Builder.CreateIsNotNull(
2365 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2366 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002367 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002368 if (ContBlock) {
2369 EmitBranch(ContBlock);
2370 EmitBlock(ContBlock, true);
2371 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002372 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002373 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002374}
2375
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002376/// The following two functions generate expressions for the loop lower
2377/// and upper bounds in case of static and dynamic (dispatch) schedule
2378/// of the associated 'for' or 'distribute' loop.
2379static std::pair<LValue, LValue>
2380emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2381 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2382 LValue LB =
2383 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2384 LValue UB =
2385 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2386 return {LB, UB};
2387}
2388
2389/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2390/// consider the lower and upper bound expressions generated by the
2391/// worksharing loop support, but we use 0 and the iteration space size as
2392/// constants
2393static std::pair<llvm::Value *, llvm::Value *>
2394emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2395 Address LB, Address UB) {
2396 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2397 const Expr *IVExpr = LS.getIterationVariable();
2398 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2399 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2400 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2401 return {LBVal, UBVal};
2402}
2403
Alexander Musmanc6388682014-12-15 07:07:06 +00002404void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002405 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002406 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2407 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002408 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002409 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2410 emitForLoopBounds,
2411 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002412 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002413 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002414 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002415 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2416 S.hasCancel());
2417 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002418
2419 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002420 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002421 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2422 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002423}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002424
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002425void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002426 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002427 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2428 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002429 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2430 emitForLoopBounds,
2431 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002432 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002433 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002434 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002435 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2436 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002437
2438 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002439 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002440 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2441 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002442}
2443
Alexey Bataev2df54a02015-03-12 08:53:29 +00002444static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2445 const Twine &Name,
2446 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002447 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002448 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002449 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002450 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002451}
2452
Alexey Bataev3392d762016-02-16 11:18:12 +00002453void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002454 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2455 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002456 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002457 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2458 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002459 auto &C = CGF.CGM.getContext();
2460 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2461 // Emit helper vars inits.
2462 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2463 CGF.Builder.getInt32(0));
2464 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2465 : CGF.Builder.getInt32(0);
2466 LValue UB =
2467 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2468 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2469 CGF.Builder.getInt32(1));
2470 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2471 CGF.Builder.getInt32(0));
2472 // Loop counter.
2473 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2474 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2475 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2476 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2477 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2478 // Generate condition for loop.
2479 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002480 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002481 // Increment for loop counter.
2482 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002483 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002484 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2485 // Iterate through all sections and emit a switch construct:
2486 // switch (IV) {
2487 // case 0:
2488 // <SectionStmt[0]>;
2489 // break;
2490 // ...
2491 // case <NumSection> - 1:
2492 // <SectionStmt[<NumSection> - 1]>;
2493 // break;
2494 // }
2495 // .omp.sections.exit:
2496 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002497 auto *SwitchStmt =
2498 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2499 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002500 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002501 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002502 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002503 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2504 CGF.EmitBlock(CaseBB);
2505 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002506 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002507 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002508 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002509 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002510 } else {
2511 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2512 CGF.EmitBlock(CaseBB);
2513 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2514 CGF.EmitStmt(Stmt);
2515 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002516 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002517 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002518 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002519
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002520 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2521 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002522 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002523 // initialization of firstprivate variables and post-update of lastprivate
2524 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002525 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2526 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2527 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002528 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002529 CGF.EmitOMPPrivateClause(S, LoopScope);
2530 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2531 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2532 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002533
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002534 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002535 OpenMPScheduleTy ScheduleKind;
2536 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002537 CGOpenMPRuntime::StaticRTInput StaticInit(
2538 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2539 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002540 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002541 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002542 // UB = min(UB, GlobalUB);
2543 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2544 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2545 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2546 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2547 // IV = LB;
2548 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2549 // while (idx <= UB) { BODY; ++idx; }
2550 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2551 [](CodeGenFunction &) {});
2552 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002553 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002554 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2555 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002556 };
2557 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002558 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002559 // Emit post-update of the reduction variables if IsLastIter != 0.
2560 emitPostUpdateForReductionClause(
2561 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2562 return CGF.Builder.CreateIsNotNull(
2563 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2564 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002565
2566 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2567 if (HasLastprivates)
2568 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002569 S, /*NoFinals=*/false,
2570 CGF.Builder.CreateIsNotNull(
2571 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002572 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002573
2574 bool HasCancel = false;
2575 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2576 HasCancel = OSD->hasCancel();
2577 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2578 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002579 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002580 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2581 HasCancel);
2582 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2583 // clause. Otherwise the barrier will be generated by the codegen for the
2584 // directive.
2585 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002586 // Emit implicit barrier to synchronize threads and avoid data races on
2587 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002588 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2589 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002590 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002591}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002592
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002593void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002594 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002595 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002596 EmitSections(S);
2597 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002598 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002599 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002600 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2601 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002602 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002603}
2604
2605void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002606 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002607 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002608 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002609 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002610 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2611 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002612}
2613
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002614void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002615 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002616 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002617 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002618 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002619 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002620 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002621 // Build a list of copyprivate variables along with helper expressions
2622 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002623 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002624 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002625 DestExprs.append(C->destination_exprs().begin(),
2626 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002627 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002628 AssignmentOps.append(C->assignment_ops().begin(),
2629 C->assignment_ops().end());
2630 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002631 // Emit code for 'single' region along with 'copyprivate' clauses
2632 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2633 Action.Enter(CGF);
2634 OMPPrivateScope SingleScope(CGF);
2635 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2636 CGF.EmitOMPPrivateClause(S, SingleScope);
2637 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002638 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002639 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002640 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002641 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002642 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2643 CopyprivateVars, DestExprs,
2644 SrcExprs, AssignmentOps);
2645 }
2646 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2647 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002648 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002649 CGM.getOpenMPRuntime().emitBarrierCall(
2650 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002651 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002652 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002653}
2654
Alexey Bataev8d690652014-12-04 07:23:53 +00002655void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002656 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2657 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002658 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002659 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002660 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002662}
2663
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002664void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002665 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2666 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002667 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002668 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002669 Expr *Hint = nullptr;
2670 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2671 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002672 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002673 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2674 S.getDirectiveName().getAsString(),
2675 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002676}
2677
Alexey Bataev671605e2015-04-13 05:28:11 +00002678void CodeGenFunction::EmitOMPParallelForDirective(
2679 const OMPParallelForDirective &S) {
2680 // Emit directive as a combined directive that consists of two implicit
2681 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002682 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002683 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002684 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2685 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002686 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002687 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2688 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002689}
2690
Alexander Musmane4e893b2014-09-23 09:33:00 +00002691void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002692 const OMPParallelForSimdDirective &S) {
2693 // Emit directive as a combined directive that consists of two implicit
2694 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002695 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002696 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2697 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002698 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002699 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2700 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002701}
2702
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002703void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002704 const OMPParallelSectionsDirective &S) {
2705 // Emit directive as a combined directive that consists of two implicit
2706 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002707 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2708 CGF.EmitSections(S);
2709 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002710 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2711 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002712}
2713
Alexey Bataev475a7442018-01-12 19:39:11 +00002714void CodeGenFunction::EmitOMPTaskBasedDirective(
2715 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2716 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2717 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002718 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002719 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002720 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002721 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002722 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002723 // Check if the task is final
2724 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2725 // If the condition constant folds and can be elided, try to avoid emitting
2726 // the condition and the dead arm of the if/else.
2727 auto *Cond = Clause->getCondition();
2728 bool CondConstant;
2729 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2730 Data.Final.setInt(CondConstant);
2731 else
2732 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2733 } else {
2734 // By default the task is not final.
2735 Data.Final.setInt(/*IntVal=*/false);
2736 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002737 // Check if the task has 'priority' clause.
2738 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002739 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002740 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002741 Data.Priority.setPointer(EmitScalarConversion(
2742 EmitScalarExpr(Prio), Prio->getType(),
2743 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2744 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002745 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002746 // The first function argument for tasks is a thread id, the second one is a
2747 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002748 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2749 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002750 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002751 auto IRef = C->varlist_begin();
2752 for (auto *IInit : C->private_copies()) {
2753 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2754 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002755 Data.PrivateVars.push_back(*IRef);
2756 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002757 }
2758 ++IRef;
2759 }
2760 }
2761 EmittedAsPrivate.clear();
2762 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002763 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002764 auto IRef = C->varlist_begin();
2765 auto IElemInitRef = C->inits().begin();
2766 for (auto *IInit : C->private_copies()) {
2767 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2768 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002769 Data.FirstprivateVars.push_back(*IRef);
2770 Data.FirstprivateCopies.push_back(IInit);
2771 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002772 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002773 ++IRef;
2774 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002775 }
2776 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002777 // Get list of lastprivate variables (for taskloops).
2778 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2779 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2780 auto IRef = C->varlist_begin();
2781 auto ID = C->destination_exprs().begin();
2782 for (auto *IInit : C->private_copies()) {
2783 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2784 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2785 Data.LastprivateVars.push_back(*IRef);
2786 Data.LastprivateCopies.push_back(IInit);
2787 }
2788 LastprivateDstsOrigs.insert(
2789 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2790 cast<DeclRefExpr>(*IRef)});
2791 ++IRef;
2792 ++ID;
2793 }
2794 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002795 SmallVector<const Expr *, 4> LHSs;
2796 SmallVector<const Expr *, 4> RHSs;
2797 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2798 auto IPriv = C->privates().begin();
2799 auto IRed = C->reduction_ops().begin();
2800 auto ILHS = C->lhs_exprs().begin();
2801 auto IRHS = C->rhs_exprs().begin();
2802 for (const auto *Ref : C->varlists()) {
2803 Data.ReductionVars.emplace_back(Ref);
2804 Data.ReductionCopies.emplace_back(*IPriv);
2805 Data.ReductionOps.emplace_back(*IRed);
2806 LHSs.emplace_back(*ILHS);
2807 RHSs.emplace_back(*IRHS);
2808 std::advance(IPriv, 1);
2809 std::advance(IRed, 1);
2810 std::advance(ILHS, 1);
2811 std::advance(IRHS, 1);
2812 }
2813 }
2814 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2815 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002816 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002817 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2818 for (auto *IRef : C->varlists())
2819 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002820 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2821 CapturedRegion](CodeGenFunction &CGF,
2822 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002823 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002824 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002825 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2826 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002827 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002828 auto *CopyFn = CGF.Builder.CreateLoad(
2829 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2830 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2831 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2832 // Map privates.
2833 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2834 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2835 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002836 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002837 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2838 Address PrivatePtr = CGF.CreateMemTemp(
2839 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2840 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2841 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002842 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002843 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002844 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2845 Address PrivatePtr =
2846 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2847 ".firstpriv.ptr.addr");
2848 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2849 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002850 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002851 for (auto *E : Data.LastprivateVars) {
2852 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2853 Address PrivatePtr =
2854 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2855 ".lastpriv.ptr.addr");
2856 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2857 CallArgs.push_back(PrivatePtr.getPointer());
2858 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002859 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2860 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002861 for (auto &&Pair : LastprivateDstsOrigs) {
2862 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2863 DeclRefExpr DRE(
2864 const_cast<VarDecl *>(OrigVD),
2865 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2866 OrigVD) != nullptr,
2867 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2868 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2869 return CGF.EmitLValue(&DRE).getAddress();
2870 });
2871 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002872 for (auto &&Pair : PrivatePtrs) {
2873 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2874 CGF.getContext().getDeclAlign(Pair.first));
2875 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2876 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002877 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002878 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002879 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002880 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2881 Data.ReductionOps);
2882 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2883 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2884 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2885 RedCG.emitSharedLValue(CGF, Cnt);
2886 RedCG.emitAggregateType(CGF, Cnt);
2887 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2888 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2889 Replacement =
2890 Address(CGF.EmitScalarConversion(
2891 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2892 CGF.getContext().getPointerType(
2893 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002894 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002895 Replacement.getAlignment());
2896 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2897 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2898 [Replacement]() { return Replacement; });
2899 // FIXME: This must removed once the runtime library is fixed.
2900 // Emit required threadprivate variables for
2901 // initilizer/combiner/finalizer.
2902 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2903 RedCG, Cnt);
2904 }
2905 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002906 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002907 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002908 SmallVector<const Expr *, 4> InRedVars;
2909 SmallVector<const Expr *, 4> InRedPrivs;
2910 SmallVector<const Expr *, 4> InRedOps;
2911 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2912 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2913 auto IPriv = C->privates().begin();
2914 auto IRed = C->reduction_ops().begin();
2915 auto ITD = C->taskgroup_descriptors().begin();
2916 for (const auto *Ref : C->varlists()) {
2917 InRedVars.emplace_back(Ref);
2918 InRedPrivs.emplace_back(*IPriv);
2919 InRedOps.emplace_back(*IRed);
2920 TaskgroupDescriptors.emplace_back(*ITD);
2921 std::advance(IPriv, 1);
2922 std::advance(IRed, 1);
2923 std::advance(ITD, 1);
2924 }
2925 }
2926 // Privatize in_reduction items here, because taskgroup descriptors must be
2927 // privatized earlier.
2928 OMPPrivateScope InRedScope(CGF);
2929 if (!InRedVars.empty()) {
2930 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2931 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2932 RedCG.emitSharedLValue(CGF, Cnt);
2933 RedCG.emitAggregateType(CGF, Cnt);
2934 // The taskgroup descriptor variable is always implicit firstprivate and
2935 // privatized already during procoessing of the firstprivates.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002936 llvm::Value *ReductionsPtr =
2937 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2938 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002939 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2940 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2941 Replacement = Address(
2942 CGF.EmitScalarConversion(
2943 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2944 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002945 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002946 Replacement.getAlignment());
2947 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2948 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2949 [Replacement]() { return Replacement; });
2950 // FIXME: This must removed once the runtime library is fixed.
2951 // Emit required threadprivate variables for
2952 // initilizer/combiner/finalizer.
2953 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2954 RedCG, Cnt);
2955 }
2956 }
2957 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002958
2959 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002960 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002961 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002962 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2963 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2964 Data.NumberOfParts);
2965 OMPLexicalScope Scope(*this, S);
2966 TaskGen(*this, OutlinedFn, Data);
2967}
2968
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002969static ImplicitParamDecl *
2970createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002971 QualType Ty, CapturedDecl *CD,
2972 SourceLocation Loc) {
2973 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2974 ImplicitParamDecl::Other);
2975 auto *OrigRef = DeclRefExpr::Create(
2976 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2977 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2978 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2979 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002980 auto *PrivateRef = DeclRefExpr::Create(
2981 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002982 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002983 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002984 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2985 ImplicitParamDecl::Other);
2986 auto *InitRef = DeclRefExpr::Create(
2987 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2988 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002989 PrivateVD->setInitStyle(VarDecl::CInit);
2990 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2991 InitRef, /*BasePath=*/nullptr,
2992 VK_RValue));
2993 Data.FirstprivateVars.emplace_back(OrigRef);
2994 Data.FirstprivateCopies.emplace_back(PrivateRef);
2995 Data.FirstprivateInits.emplace_back(InitRef);
2996 return OrigVD;
2997}
2998
2999void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3000 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3001 OMPTargetDataInfo &InputInfo) {
3002 // Emit outlined function for task construct.
3003 auto CS = S.getCapturedStmt(OMPD_task);
3004 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3005 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3006 auto *I = CS->getCapturedDecl()->param_begin();
3007 auto *PartId = std::next(I);
3008 auto *TaskT = std::next(I, 4);
3009 OMPTaskDataTy Data;
3010 // The task is not final.
3011 Data.Final.setInt(/*IntVal=*/false);
3012 // Get list of firstprivate variables.
3013 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3014 auto IRef = C->varlist_begin();
3015 auto IElemInitRef = C->inits().begin();
3016 for (auto *IInit : C->private_copies()) {
3017 Data.FirstprivateVars.push_back(*IRef);
3018 Data.FirstprivateCopies.push_back(IInit);
3019 Data.FirstprivateInits.push_back(*IElemInitRef);
3020 ++IRef;
3021 ++IElemInitRef;
3022 }
3023 }
3024 OMPPrivateScope TargetScope(*this);
3025 VarDecl *BPVD = nullptr;
3026 VarDecl *PVD = nullptr;
3027 VarDecl *SVD = nullptr;
3028 if (InputInfo.NumberOfTargetItems > 0) {
3029 auto *CD = CapturedDecl::Create(
3030 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3031 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3032 QualType BaseAndPointersType = getContext().getConstantArrayType(
3033 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3034 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003035 BPVD = createImplicitFirstprivateForType(
3036 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3037 PVD = createImplicitFirstprivateForType(
3038 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003039 QualType SizesType = getContext().getConstantArrayType(
3040 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3041 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003042 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3043 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003044 TargetScope.addPrivate(
3045 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3046 TargetScope.addPrivate(PVD,
3047 [&InputInfo]() { return InputInfo.PointersArray; });
3048 TargetScope.addPrivate(SVD,
3049 [&InputInfo]() { return InputInfo.SizesArray; });
3050 }
3051 (void)TargetScope.Privatize();
3052 // Build list of dependences.
3053 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3054 for (auto *IRef : C->varlists())
3055 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3056 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3057 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3058 // Set proper addresses for generated private copies.
3059 OMPPrivateScope Scope(CGF);
3060 if (!Data.FirstprivateVars.empty()) {
3061 enum { PrivatesParam = 2, CopyFnParam = 3 };
3062 auto *CopyFn = CGF.Builder.CreateLoad(
3063 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3064 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3065 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3066 // Map privates.
3067 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3068 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3069 CallArgs.push_back(PrivatesPtr);
3070 for (auto *E : Data.FirstprivateVars) {
3071 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3072 Address PrivatePtr =
3073 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3074 ".firstpriv.ptr.addr");
3075 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3076 CallArgs.push_back(PrivatePtr.getPointer());
3077 }
3078 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3079 CopyFn, CallArgs);
3080 for (auto &&Pair : PrivatePtrs) {
3081 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3082 CGF.getContext().getDeclAlign(Pair.first));
3083 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3084 }
3085 }
3086 // Privatize all private variables except for in_reduction items.
3087 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003088 if (InputInfo.NumberOfTargetItems > 0) {
3089 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3090 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3091 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3092 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3093 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3094 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3095 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003096
3097 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003098 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003099 BodyGen(CGF);
3100 };
3101 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3102 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3103 Data.NumberOfParts);
3104 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3105 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3106 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3107 SourceLocation());
3108
3109 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3110 SharedsTy, CapturedStruct, &IfCond, Data);
3111}
3112
Alexey Bataev7292c292016-04-25 12:22:29 +00003113void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3114 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003115 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003116 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003117 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003118 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003119 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3120 if (C->getNameModifier() == OMPD_unknown ||
3121 C->getNameModifier() == OMPD_task) {
3122 IfCond = C->getCondition();
3123 break;
3124 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003125 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003126
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003127 OMPTaskDataTy Data;
3128 // Check if we should emit tied or untied task.
3129 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003130 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3131 CGF.EmitStmt(CS->getCapturedStmt());
3132 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003133 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003134 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003135 const OMPTaskDataTy &Data) {
3136 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3137 SharedsTy, CapturedStruct, IfCond,
3138 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003139 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003140 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003141}
3142
Alexey Bataev9f797f32015-02-05 05:57:51 +00003143void CodeGenFunction::EmitOMPTaskyieldDirective(
3144 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003145 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003146}
3147
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003148void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003149 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003150}
3151
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003152void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3153 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003154}
3155
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003156void CodeGenFunction::EmitOMPTaskgroupDirective(
3157 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003158 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3159 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003160 if (const Expr *E = S.getReductionRef()) {
3161 SmallVector<const Expr *, 4> LHSs;
3162 SmallVector<const Expr *, 4> RHSs;
3163 OMPTaskDataTy Data;
3164 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3165 auto IPriv = C->privates().begin();
3166 auto IRed = C->reduction_ops().begin();
3167 auto ILHS = C->lhs_exprs().begin();
3168 auto IRHS = C->rhs_exprs().begin();
3169 for (const auto *Ref : C->varlists()) {
3170 Data.ReductionVars.emplace_back(Ref);
3171 Data.ReductionCopies.emplace_back(*IPriv);
3172 Data.ReductionOps.emplace_back(*IRed);
3173 LHSs.emplace_back(*ILHS);
3174 RHSs.emplace_back(*IRHS);
3175 std::advance(IPriv, 1);
3176 std::advance(IRed, 1);
3177 std::advance(ILHS, 1);
3178 std::advance(IRHS, 1);
3179 }
3180 }
3181 llvm::Value *ReductionDesc =
3182 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3183 LHSs, RHSs, Data);
3184 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3185 CGF.EmitVarDecl(*VD);
3186 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3187 /*Volatile=*/false, E->getType());
3188 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003189 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003190 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003191 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003192 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3193}
3194
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003195void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003196 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003197 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003198 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3199 FlushClause->varlist_end());
3200 }
3201 return llvm::None;
3202 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003203}
3204
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003205void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3206 const CodeGenLoopTy &CodeGenLoop,
3207 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003208 // Emit the loop iteration variable.
3209 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3210 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3211 EmitVarDecl(*IVDecl);
3212
3213 // Emit the iterations count variable.
3214 // If it is not a variable, Sema decided to calculate iterations count on each
3215 // iteration (e.g., it is foldable into a constant).
3216 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3217 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3218 // Emit calculation of the iterations count.
3219 EmitIgnoredExpr(S.getCalcLastIteration());
3220 }
3221
3222 auto &RT = CGM.getOpenMPRuntime();
3223
Carlo Bertolli962bb802017-01-03 18:24:42 +00003224 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003225 // Check pre-condition.
3226 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003227 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003228 // Skip the entire loop if we don't meet the precondition.
3229 // If the condition constant folds and can be elided, avoid emitting the
3230 // whole loop.
3231 bool CondConstant;
3232 llvm::BasicBlock *ContBlock = nullptr;
3233 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3234 if (!CondConstant)
3235 return;
3236 } else {
3237 auto *ThenBlock = createBasicBlock("omp.precond.then");
3238 ContBlock = createBasicBlock("omp.precond.end");
3239 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3240 getProfileCount(&S));
3241 EmitBlock(ThenBlock);
3242 incrementProfileCounter(&S);
3243 }
3244
Alexey Bataev617db5f2017-12-04 15:38:33 +00003245 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003246 // Emit 'then' code.
3247 {
3248 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003249
3250 LValue LB = EmitOMPHelperVar(
3251 *this, cast<DeclRefExpr>(
3252 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3253 ? S.getCombinedLowerBoundVariable()
3254 : S.getLowerBoundVariable())));
3255 LValue UB = EmitOMPHelperVar(
3256 *this, cast<DeclRefExpr>(
3257 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3258 ? S.getCombinedUpperBoundVariable()
3259 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003260 LValue ST =
3261 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3262 LValue IL =
3263 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3264
3265 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003266 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003267 // Emit implicit barrier to synchronize threads and avoid data races
3268 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003269 // lastprivate variables.
3270 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003271 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3272 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003273 }
3274 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003275 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003276 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3277 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003278 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003279 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003280 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003281 (void)LoopScope.Privatize();
3282
3283 // Detect the distribute schedule kind and chunk.
3284 llvm::Value *Chunk = nullptr;
3285 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3286 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3287 ScheduleKind = C->getDistScheduleKind();
3288 if (const auto *Ch = C->getChunkSize()) {
3289 Chunk = EmitScalarExpr(Ch);
3290 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003291 S.getIterationVariable()->getType(),
3292 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003293 }
3294 }
3295 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3296 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3297
3298 // OpenMP [2.10.8, distribute Construct, Description]
3299 // If dist_schedule is specified, kind must be static. If specified,
3300 // iterations are divided into chunks of size chunk_size, chunks are
3301 // assigned to the teams of the league in a round-robin fashion in the
3302 // order of the team number. When no chunk_size is specified, the
3303 // iteration space is divided into chunks that are approximately equal
3304 // in size, and at most one chunk is distributed to each team of the
3305 // league. The size of the chunks is unspecified in this case.
3306 if (RT.isStaticNonchunked(ScheduleKind,
3307 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003308 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3309 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003310 CGOpenMPRuntime::StaticRTInput StaticInit(
3311 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3312 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003313 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003314 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003315 auto LoopExit =
3316 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3317 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003318 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3319 ? S.getCombinedEnsureUpperBound()
3320 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003321 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003322 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3323 ? S.getCombinedInit()
3324 : S.getInit());
3325
3326 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3327 ? S.getCombinedCond()
3328 : S.getCond();
3329
3330 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003331 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003332 // when combined with 'for' (e.g. as in 'distribute parallel for')
3333 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3334 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3335 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3336 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003337 },
3338 [](CodeGenFunction &) {});
3339 EmitBlock(LoopExit.getBlock());
3340 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003341 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003342 } else {
3343 // Emit the outer loop, which requests its work chunk [LB..UB] from
3344 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003345 const OMPLoopArguments LoopArguments = {
3346 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3347 Chunk};
3348 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3349 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003350 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003351 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3352 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3353 return CGF.Builder.CreateIsNotNull(
3354 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3355 });
3356 }
3357 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3358 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3359 isOpenMPSimdDirective(S.getDirectiveKind())) {
3360 ReductionKind = OMPD_parallel_for_simd;
3361 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3362 ReductionKind = OMPD_parallel_for;
3363 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3364 ReductionKind = OMPD_simd;
3365 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3366 S.hasClausesOfKind<OMPReductionClause>()) {
3367 llvm_unreachable(
3368 "No reduction clauses is allowed in distribute directive.");
3369 }
3370 EmitOMPReductionClauseFinal(S, ReductionKind);
3371 // Emit post-update of the reduction variables if IsLastIter != 0.
3372 emitPostUpdateForReductionClause(
3373 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3374 return CGF.Builder.CreateIsNotNull(
3375 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3376 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003377 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003378 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003379 EmitOMPLastprivateClauseFinal(
3380 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003381 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3382 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003383 }
3384
3385 // We're now done with the loop, so jump to the continuation block.
3386 if (ContBlock) {
3387 EmitBranch(ContBlock);
3388 EmitBlock(ContBlock, true);
3389 }
3390 }
3391}
3392
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003393void CodeGenFunction::EmitOMPDistributeDirective(
3394 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003395 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003396
3397 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003398 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003399 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003400 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003401}
3402
Alexey Bataev5f600d62015-09-29 03:48:57 +00003403static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3404 const CapturedStmt *S) {
3405 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3406 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3407 CGF.CapturedStmtInfo = &CapStmtInfo;
3408 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3409 Fn->addFnAttr(llvm::Attribute::NoInline);
3410 return Fn;
3411}
3412
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003413void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003414 if (S.hasClausesOfKind<OMPDependClause>()) {
3415 assert(!S.getAssociatedStmt() &&
3416 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003417 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3418 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003419 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003420 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003421 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003422 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3423 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003424 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003425 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003426 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3427 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3428 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003429 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3430 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003431 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003432 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003433 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003434 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003435 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003436 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003437 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003438}
3439
Alexey Bataevb57056f2015-01-22 06:17:56 +00003440static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003441 QualType SrcType, QualType DestType,
3442 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003443 assert(CGF.hasScalarEvaluationKind(DestType) &&
3444 "DestType must have scalar evaluation kind.");
3445 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3446 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003447 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3448 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003449 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003450 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003451}
3452
3453static CodeGenFunction::ComplexPairTy
3454convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003455 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003456 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3457 "DestType must have complex evaluation kind.");
3458 CodeGenFunction::ComplexPairTy ComplexVal;
3459 if (Val.isScalar()) {
3460 // Convert the input element to the element type of the complex.
3461 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003462 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3463 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003464 ComplexVal = CodeGenFunction::ComplexPairTy(
3465 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3466 } else {
3467 assert(Val.isComplex() && "Must be a scalar or complex.");
3468 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3469 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3470 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003471 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003472 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003473 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003474 }
3475 return ComplexVal;
3476}
3477
Alexey Bataev5e018f92015-04-23 06:35:10 +00003478static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3479 LValue LVal, RValue RVal) {
3480 if (LVal.isGlobalReg()) {
3481 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3482 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003483 CGF.EmitAtomicStore(RVal, LVal,
3484 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3485 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003486 LVal.isVolatile(), /*IsInit=*/false);
3487 }
3488}
3489
Alexey Bataev8524d152016-01-21 12:35:58 +00003490void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3491 QualType RValTy, SourceLocation Loc) {
3492 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003493 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003494 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3495 *this, RVal, RValTy, LVal.getType(), Loc)),
3496 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003497 break;
3498 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003499 EmitStoreOfComplex(
3500 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003501 /*isInit=*/false);
3502 break;
3503 case TEK_Aggregate:
3504 llvm_unreachable("Must be a scalar or complex.");
3505 }
3506}
3507
Alexey Bataevb57056f2015-01-22 06:17:56 +00003508static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3509 const Expr *X, const Expr *V,
3510 SourceLocation Loc) {
3511 // v = x;
3512 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3513 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3514 LValue XLValue = CGF.EmitLValue(X);
3515 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003516 RValue Res = XLValue.isGlobalReg()
3517 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003518 : CGF.EmitAtomicLoad(
3519 XLValue, Loc,
3520 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3521 : llvm::AtomicOrdering::Monotonic,
3522 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003523 // OpenMP, 2.12.6, atomic Construct
3524 // Any atomic construct with a seq_cst clause forces the atomically
3525 // performed operation to include an implicit flush operation without a
3526 // list.
3527 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003528 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003529 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003530}
3531
Alexey Bataevb8329262015-02-27 06:33:30 +00003532static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3533 const Expr *X, const Expr *E,
3534 SourceLocation Loc) {
3535 // x = expr;
3536 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003537 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003538 // OpenMP, 2.12.6, atomic Construct
3539 // Any atomic construct with a seq_cst clause forces the atomically
3540 // performed operation to include an implicit flush operation without a
3541 // list.
3542 if (IsSeqCst)
3543 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3544}
3545
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003546static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3547 RValue Update,
3548 BinaryOperatorKind BO,
3549 llvm::AtomicOrdering AO,
3550 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003551 auto &Context = CGF.CGM.getContext();
3552 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003553 // expression is simple and atomic is allowed for the given type for the
3554 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003555 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003556 !Update.getScalarVal()->getType()->isIntegerTy() ||
3557 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3558 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003559 X.getAddress().getElementType())) ||
3560 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003561 !Context.getTargetInfo().hasBuiltinAtomic(
3562 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003563 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003564
3565 llvm::AtomicRMWInst::BinOp RMWOp;
3566 switch (BO) {
3567 case BO_Add:
3568 RMWOp = llvm::AtomicRMWInst::Add;
3569 break;
3570 case BO_Sub:
3571 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003572 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003573 RMWOp = llvm::AtomicRMWInst::Sub;
3574 break;
3575 case BO_And:
3576 RMWOp = llvm::AtomicRMWInst::And;
3577 break;
3578 case BO_Or:
3579 RMWOp = llvm::AtomicRMWInst::Or;
3580 break;
3581 case BO_Xor:
3582 RMWOp = llvm::AtomicRMWInst::Xor;
3583 break;
3584 case BO_LT:
3585 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3586 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3587 : llvm::AtomicRMWInst::Max)
3588 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3589 : llvm::AtomicRMWInst::UMax);
3590 break;
3591 case BO_GT:
3592 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3593 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3594 : llvm::AtomicRMWInst::Min)
3595 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3596 : llvm::AtomicRMWInst::UMin);
3597 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003598 case BO_Assign:
3599 RMWOp = llvm::AtomicRMWInst::Xchg;
3600 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003601 case BO_Mul:
3602 case BO_Div:
3603 case BO_Rem:
3604 case BO_Shl:
3605 case BO_Shr:
3606 case BO_LAnd:
3607 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003608 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003609 case BO_PtrMemD:
3610 case BO_PtrMemI:
3611 case BO_LE:
3612 case BO_GE:
3613 case BO_EQ:
3614 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003615 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003616 case BO_AddAssign:
3617 case BO_SubAssign:
3618 case BO_AndAssign:
3619 case BO_OrAssign:
3620 case BO_XorAssign:
3621 case BO_MulAssign:
3622 case BO_DivAssign:
3623 case BO_RemAssign:
3624 case BO_ShlAssign:
3625 case BO_ShrAssign:
3626 case BO_Comma:
3627 llvm_unreachable("Unsupported atomic update operation");
3628 }
3629 auto *UpdateVal = Update.getScalarVal();
3630 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3631 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003632 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003633 X.getType()->hasSignedIntegerRepresentation());
3634 }
John McCall7f416cc2015-09-08 08:05:57 +00003635 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003636 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003637}
3638
Alexey Bataev5e018f92015-04-23 06:35:10 +00003639std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003640 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3641 llvm::AtomicOrdering AO, SourceLocation Loc,
3642 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3643 // Update expressions are allowed to have the following forms:
3644 // x binop= expr; -> xrval + expr;
3645 // x++, ++x -> xrval + 1;
3646 // x--, --x -> xrval - 1;
3647 // x = x binop expr; -> xrval binop expr
3648 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003649 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3650 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003651 if (X.isGlobalReg()) {
3652 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3653 // 'xrval'.
3654 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3655 } else {
3656 // Perform compare-and-swap procedure.
3657 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003658 }
3659 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003660 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003661}
3662
3663static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3664 const Expr *X, const Expr *E,
3665 const Expr *UE, bool IsXLHSInRHSPart,
3666 SourceLocation Loc) {
3667 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3668 "Update expr in 'atomic update' must be a binary operator.");
3669 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3670 // Update expressions are allowed to have the following forms:
3671 // x binop= expr; -> xrval + expr;
3672 // x++, ++x -> xrval + 1;
3673 // x--, --x -> xrval - 1;
3674 // x = x binop expr; -> xrval binop expr
3675 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003676 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003677 LValue XLValue = CGF.EmitLValue(X);
3678 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003679 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3680 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003681 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3682 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3683 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3684 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3685 auto Gen =
3686 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3687 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3688 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3689 return CGF.EmitAnyExpr(UE);
3690 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003691 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3692 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3693 // OpenMP, 2.12.6, atomic Construct
3694 // Any atomic construct with a seq_cst clause forces the atomically
3695 // performed operation to include an implicit flush operation without a
3696 // list.
3697 if (IsSeqCst)
3698 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3699}
3700
3701static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003702 QualType SourceType, QualType ResType,
3703 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003704 switch (CGF.getEvaluationKind(ResType)) {
3705 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003706 return RValue::get(
3707 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003708 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003709 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003710 return RValue::getComplex(Res.first, Res.second);
3711 }
3712 case TEK_Aggregate:
3713 break;
3714 }
3715 llvm_unreachable("Must be a scalar or complex.");
3716}
3717
3718static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3719 bool IsPostfixUpdate, const Expr *V,
3720 const Expr *X, const Expr *E,
3721 const Expr *UE, bool IsXLHSInRHSPart,
3722 SourceLocation Loc) {
3723 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3724 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3725 RValue NewVVal;
3726 LValue VLValue = CGF.EmitLValue(V);
3727 LValue XLValue = CGF.EmitLValue(X);
3728 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003729 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3730 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003731 QualType NewVValType;
3732 if (UE) {
3733 // 'x' is updated with some additional value.
3734 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3735 "Update expr in 'atomic capture' must be a binary operator.");
3736 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3737 // Update expressions are allowed to have the following forms:
3738 // x binop= expr; -> xrval + expr;
3739 // x++, ++x -> xrval + 1;
3740 // x--, --x -> xrval - 1;
3741 // x = x binop expr; -> xrval binop expr
3742 // x = expr Op x; - > expr binop xrval;
3743 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3744 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3745 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3746 NewVValType = XRValExpr->getType();
3747 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3748 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003749 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003750 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3751 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3752 RValue Res = CGF.EmitAnyExpr(UE);
3753 NewVVal = IsPostfixUpdate ? XRValue : Res;
3754 return Res;
3755 };
3756 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3757 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3758 if (Res.first) {
3759 // 'atomicrmw' instruction was generated.
3760 if (IsPostfixUpdate) {
3761 // Use old value from 'atomicrmw'.
3762 NewVVal = Res.second;
3763 } else {
3764 // 'atomicrmw' does not provide new value, so evaluate it using old
3765 // value of 'x'.
3766 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3767 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3768 NewVVal = CGF.EmitAnyExpr(UE);
3769 }
3770 }
3771 } else {
3772 // 'x' is simply rewritten with some 'expr'.
3773 NewVValType = X->getType().getNonReferenceType();
3774 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003775 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003776 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003777 NewVVal = XRValue;
3778 return ExprRValue;
3779 };
3780 // Try to perform atomicrmw xchg, otherwise simple exchange.
3781 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3782 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3783 Loc, Gen);
3784 if (Res.first) {
3785 // 'atomicrmw' instruction was generated.
3786 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3787 }
3788 }
3789 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003790 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003791 // OpenMP, 2.12.6, atomic Construct
3792 // Any atomic construct with a seq_cst clause forces the atomically
3793 // performed operation to include an implicit flush operation without a
3794 // list.
3795 if (IsSeqCst)
3796 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3797}
3798
Alexey Bataevb57056f2015-01-22 06:17:56 +00003799static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003800 bool IsSeqCst, bool IsPostfixUpdate,
3801 const Expr *X, const Expr *V, const Expr *E,
3802 const Expr *UE, bool IsXLHSInRHSPart,
3803 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003804 switch (Kind) {
3805 case OMPC_read:
3806 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3807 break;
3808 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003809 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3810 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003811 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003812 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003813 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3814 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003815 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003816 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3817 IsXLHSInRHSPart, Loc);
3818 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003819 case OMPC_if:
3820 case OMPC_final:
3821 case OMPC_num_threads:
3822 case OMPC_private:
3823 case OMPC_firstprivate:
3824 case OMPC_lastprivate:
3825 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003826 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003827 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003828 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003829 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003830 case OMPC_collapse:
3831 case OMPC_default:
3832 case OMPC_seq_cst:
3833 case OMPC_shared:
3834 case OMPC_linear:
3835 case OMPC_aligned:
3836 case OMPC_copyin:
3837 case OMPC_copyprivate:
3838 case OMPC_flush:
3839 case OMPC_proc_bind:
3840 case OMPC_schedule:
3841 case OMPC_ordered:
3842 case OMPC_nowait:
3843 case OMPC_untied:
3844 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003845 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003846 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003847 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003848 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003849 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003850 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003851 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003852 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003853 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003854 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003855 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003856 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003857 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003858 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003859 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003860 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003861 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003862 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003863 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003864 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003865 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3866 }
3867}
3868
3869void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003870 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003871 OpenMPClauseKind Kind = OMPC_unknown;
3872 for (auto *C : S.clauses()) {
3873 // Find first clause (skip seq_cst clause, if it is first).
3874 if (C->getClauseKind() != OMPC_seq_cst) {
3875 Kind = C->getClauseKind();
3876 break;
3877 }
3878 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003879
Alexey Bataev475a7442018-01-12 19:39:11 +00003880 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003881 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003882 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003883 }
3884 // Processing for statements under 'atomic capture'.
3885 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3886 for (const auto *C : Compound->body()) {
3887 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3888 enterFullExpression(EWC);
3889 }
3890 }
3891 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003892
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003893 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3894 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003895 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003896 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3897 S.getV(), S.getExpr(), S.getUpdateExpr(),
3898 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003899 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003900 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003901 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003902}
3903
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003904static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3905 const OMPExecutableDirective &S,
3906 const RegionCodeGenTy &CodeGen) {
3907 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3908 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003909
Samuel Antaoee8fb302016-01-06 13:42:12 +00003910 llvm::Function *Fn = nullptr;
3911 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003912
Samuel Antaobed3c462015-10-02 16:14:20 +00003913 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003914 // Check for the at most one if clause associated with the target region.
3915 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3916 if (C->getNameModifier() == OMPD_unknown ||
3917 C->getNameModifier() == OMPD_target) {
3918 IfCond = C->getCondition();
3919 break;
3920 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003921 }
3922
3923 // Check if we have any device clause associated with the directive.
3924 const Expr *Device = nullptr;
3925 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3926 Device = C->getDevice();
3927 }
3928
Samuel Antaoee8fb302016-01-06 13:42:12 +00003929 // Check if we have an if clause whose conditional always evaluates to false
3930 // or if we do not have any targets specified. If so the target region is not
3931 // an offload entry point.
3932 bool IsOffloadEntry = true;
3933 if (IfCond) {
3934 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003935 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003936 IsOffloadEntry = false;
3937 }
3938 if (CGM.getLangOpts().OMPTargetTriples.empty())
3939 IsOffloadEntry = false;
3940
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003941 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 StringRef ParentName;
3943 // In case we have Ctors/Dtors we use the complete type variant to produce
3944 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003945 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003946 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003947 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3949 else
3950 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003951 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003952
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003953 // Emit target region as a standalone region.
3954 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3955 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003956 OMPLexicalScope Scope(CGF, S, OMPD_task);
3957 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003958}
3959
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003960static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3961 PrePostActionTy &Action) {
3962 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3963 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3964 CGF.EmitOMPPrivateClause(S, PrivateScope);
3965 (void)PrivateScope.Privatize();
3966
3967 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003968 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003969}
3970
3971void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3972 StringRef ParentName,
3973 const OMPTargetDirective &S) {
3974 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3975 emitTargetRegion(CGF, S, Action);
3976 };
3977 llvm::Function *Fn;
3978 llvm::Constant *Addr;
3979 // Emit target region as a standalone region.
3980 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3981 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3982 assert(Fn && Addr && "Target device function emission failed.");
3983}
3984
3985void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3986 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3987 emitTargetRegion(CGF, S, Action);
3988 };
3989 emitCommonOMPTargetDirective(*this, S, CodeGen);
3990}
3991
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003992static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3993 const OMPExecutableDirective &S,
3994 OpenMPDirectiveKind InnermostKind,
3995 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003996 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3997 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3998 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003999
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004000 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4001 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004002 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004003 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4004 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004005
Carlo Bertollic6872252016-04-04 15:55:02 +00004006 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4007 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004008 }
4009
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004010 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004011 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4012 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004013 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4014 CapturedVars);
4015}
4016
4017void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004018 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004019 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004020 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004021 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4022 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004023 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004024 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004025 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004026 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004027 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004028 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004029 emitPostUpdateForReductionClause(
4030 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004031}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004032
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004033static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4034 const OMPTargetTeamsDirective &S) {
4035 auto *CS = S.getCapturedStmt(OMPD_teams);
4036 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004037 // Emit teams region as a standalone region.
4038 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4039 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4040 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4041 CGF.EmitOMPPrivateClause(S, PrivateScope);
4042 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4043 (void)PrivateScope.Privatize();
4044 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004045 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004046 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004047 };
4048 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004049 emitPostUpdateForReductionClause(
4050 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004051}
4052
4053void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4054 CodeGenModule &CGM, StringRef ParentName,
4055 const OMPTargetTeamsDirective &S) {
4056 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4057 emitTargetTeamsRegion(CGF, Action, S);
4058 };
4059 llvm::Function *Fn;
4060 llvm::Constant *Addr;
4061 // Emit target region as a standalone region.
4062 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4063 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4064 assert(Fn && Addr && "Target device function emission failed.");
4065}
4066
4067void CodeGenFunction::EmitOMPTargetTeamsDirective(
4068 const OMPTargetTeamsDirective &S) {
4069 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4070 emitTargetTeamsRegion(CGF, Action, S);
4071 };
4072 emitCommonOMPTargetDirective(*this, S, CodeGen);
4073}
4074
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004075static void
4076emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4077 const OMPTargetTeamsDistributeDirective &S) {
4078 Action.Enter(CGF);
4079 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4080 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4081 };
4082
4083 // Emit teams region as a standalone region.
4084 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4085 PrePostActionTy &) {
4086 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4087 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4088 (void)PrivateScope.Privatize();
4089 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4090 CodeGenDistribute);
4091 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4092 };
4093 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4094 emitPostUpdateForReductionClause(CGF, S,
4095 [](CodeGenFunction &) { return nullptr; });
4096}
4097
4098void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4099 CodeGenModule &CGM, StringRef ParentName,
4100 const OMPTargetTeamsDistributeDirective &S) {
4101 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4102 emitTargetTeamsDistributeRegion(CGF, Action, S);
4103 };
4104 llvm::Function *Fn;
4105 llvm::Constant *Addr;
4106 // Emit target region as a standalone region.
4107 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4108 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4109 assert(Fn && Addr && "Target device function emission failed.");
4110}
4111
4112void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4113 const OMPTargetTeamsDistributeDirective &S) {
4114 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4115 emitTargetTeamsDistributeRegion(CGF, Action, S);
4116 };
4117 emitCommonOMPTargetDirective(*this, S, CodeGen);
4118}
4119
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004120static void emitTargetTeamsDistributeSimdRegion(
4121 CodeGenFunction &CGF, PrePostActionTy &Action,
4122 const OMPTargetTeamsDistributeSimdDirective &S) {
4123 Action.Enter(CGF);
4124 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4125 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4126 };
4127
4128 // Emit teams region as a standalone region.
4129 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4130 PrePostActionTy &) {
4131 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4132 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4133 (void)PrivateScope.Privatize();
4134 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4135 CodeGenDistribute);
4136 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4137 };
4138 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4139 emitPostUpdateForReductionClause(CGF, S,
4140 [](CodeGenFunction &) { return nullptr; });
4141}
4142
4143void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4144 CodeGenModule &CGM, StringRef ParentName,
4145 const OMPTargetTeamsDistributeSimdDirective &S) {
4146 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4147 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4148 };
4149 llvm::Function *Fn;
4150 llvm::Constant *Addr;
4151 // Emit target region as a standalone region.
4152 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4153 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4154 assert(Fn && Addr && "Target device function emission failed.");
4155}
4156
4157void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4158 const OMPTargetTeamsDistributeSimdDirective &S) {
4159 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4160 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4161 };
4162 emitCommonOMPTargetDirective(*this, S, CodeGen);
4163}
4164
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004165void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4166 const OMPTeamsDistributeDirective &S) {
4167
4168 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4169 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4170 };
4171
4172 // Emit teams region as a standalone region.
4173 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4174 PrePostActionTy &) {
4175 OMPPrivateScope PrivateScope(CGF);
4176 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4177 (void)PrivateScope.Privatize();
4178 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4179 CodeGenDistribute);
4180 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4181 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004182 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004183 emitPostUpdateForReductionClause(*this, S,
4184 [](CodeGenFunction &) { return nullptr; });
4185}
4186
Alexey Bataev999277a2017-12-06 14:31:09 +00004187void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4188 const OMPTeamsDistributeSimdDirective &S) {
4189 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4190 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4191 };
4192
4193 // Emit teams region as a standalone region.
4194 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4195 PrePostActionTy &) {
4196 OMPPrivateScope PrivateScope(CGF);
4197 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4198 (void)PrivateScope.Privatize();
4199 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4200 CodeGenDistribute);
4201 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4202 };
4203 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4204 emitPostUpdateForReductionClause(*this, S,
4205 [](CodeGenFunction &) { return nullptr; });
4206}
4207
Carlo Bertolli62fae152017-11-20 20:46:39 +00004208void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4209 const OMPTeamsDistributeParallelForDirective &S) {
4210 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4211 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4212 S.getDistInc());
4213 };
4214
4215 // Emit teams region as a standalone region.
4216 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4217 PrePostActionTy &) {
4218 OMPPrivateScope PrivateScope(CGF);
4219 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4220 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004221 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4222 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004223 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4224 };
4225 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4226 emitPostUpdateForReductionClause(*this, S,
4227 [](CodeGenFunction &) { return nullptr; });
4228}
4229
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004230void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4231 const OMPTeamsDistributeParallelForSimdDirective &S) {
4232 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4233 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4234 S.getDistInc());
4235 };
4236
4237 // Emit teams region as a standalone region.
4238 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4239 PrePostActionTy &) {
4240 OMPPrivateScope PrivateScope(CGF);
4241 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4242 (void)PrivateScope.Privatize();
4243 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4244 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4245 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4246 };
4247 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4248 emitPostUpdateForReductionClause(*this, S,
4249 [](CodeGenFunction &) { return nullptr; });
4250}
4251
Carlo Bertolli52978c32018-01-03 21:12:44 +00004252static void emitTargetTeamsDistributeParallelForRegion(
4253 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4254 PrePostActionTy &Action) {
4255 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4256 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4257 S.getDistInc());
4258 };
4259
4260 // Emit teams region as a standalone region.
4261 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4262 PrePostActionTy &) {
4263 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4264 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4265 (void)PrivateScope.Privatize();
4266 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4267 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4268 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4269 };
4270
4271 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4272 CodeGenTeams);
4273 emitPostUpdateForReductionClause(CGF, S,
4274 [](CodeGenFunction &) { return nullptr; });
4275}
4276
4277void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4278 CodeGenModule &CGM, StringRef ParentName,
4279 const OMPTargetTeamsDistributeParallelForDirective &S) {
4280 // Emit SPMD target teams distribute parallel for region as a standalone
4281 // region.
4282 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4283 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4284 };
4285 llvm::Function *Fn;
4286 llvm::Constant *Addr;
4287 // Emit target region as a standalone region.
4288 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4289 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4290 assert(Fn && Addr && "Target device function emission failed.");
4291}
4292
4293void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4294 const OMPTargetTeamsDistributeParallelForDirective &S) {
4295 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4296 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4297 };
4298 emitCommonOMPTargetDirective(*this, S, CodeGen);
4299}
4300
Alexey Bataev647dd842018-01-15 20:59:40 +00004301static void emitTargetTeamsDistributeParallelForSimdRegion(
4302 CodeGenFunction &CGF,
4303 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4304 PrePostActionTy &Action) {
4305 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4306 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4307 S.getDistInc());
4308 };
4309
4310 // Emit teams region as a standalone region.
4311 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4312 PrePostActionTy &) {
4313 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4314 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4315 (void)PrivateScope.Privatize();
4316 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4317 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4318 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4319 };
4320
4321 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4322 CodeGenTeams);
4323 emitPostUpdateForReductionClause(CGF, S,
4324 [](CodeGenFunction &) { return nullptr; });
4325}
4326
4327void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4328 CodeGenModule &CGM, StringRef ParentName,
4329 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4330 // Emit SPMD target teams distribute parallel for simd region as a standalone
4331 // region.
4332 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4333 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4334 };
4335 llvm::Function *Fn;
4336 llvm::Constant *Addr;
4337 // Emit target region as a standalone region.
4338 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4339 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4340 assert(Fn && Addr && "Target device function emission failed.");
4341}
4342
4343void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4344 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4345 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4346 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4347 };
4348 emitCommonOMPTargetDirective(*this, S, CodeGen);
4349}
4350
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004351void CodeGenFunction::EmitOMPCancellationPointDirective(
4352 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004353 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4354 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004355}
4356
Alexey Bataev80909872015-07-02 11:25:17 +00004357void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004358 const Expr *IfCond = nullptr;
4359 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4360 if (C->getNameModifier() == OMPD_unknown ||
4361 C->getNameModifier() == OMPD_cancel) {
4362 IfCond = C->getCondition();
4363 break;
4364 }
4365 }
4366 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004367 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004368}
4369
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004370CodeGenFunction::JumpDest
4371CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004372 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4373 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004374 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004375 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004376 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4377 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004378 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004379 Kind == OMPD_teams_distribute_parallel_for ||
4380 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004381 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004382}
Michael Wong65f367f2015-07-21 13:44:28 +00004383
Samuel Antaocc10b852016-07-28 14:23:26 +00004384void CodeGenFunction::EmitOMPUseDevicePtrClause(
4385 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4386 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4387 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4388 auto OrigVarIt = C.varlist_begin();
4389 auto InitIt = C.inits().begin();
4390 for (auto PvtVarIt : C.private_copies()) {
4391 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4392 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4393 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4394
4395 // In order to identify the right initializer we need to match the
4396 // declaration used by the mapping logic. In some cases we may get
4397 // OMPCapturedExprDecl that refers to the original declaration.
4398 const ValueDecl *MatchingVD = OrigVD;
4399 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4400 // OMPCapturedExprDecl are used to privative fields of the current
4401 // structure.
4402 auto *ME = cast<MemberExpr>(OED->getInit());
4403 assert(isa<CXXThisExpr>(ME->getBase()) &&
4404 "Base should be the current struct!");
4405 MatchingVD = ME->getMemberDecl();
4406 }
4407
4408 // If we don't have information about the current list item, move on to
4409 // the next one.
4410 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4411 if (InitAddrIt == CaptureDeviceAddrMap.end())
4412 continue;
4413
4414 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4415 // Initialize the temporary initialization variable with the address we
4416 // get from the runtime library. We have to cast the source address
4417 // because it is always a void *. References are materialized in the
4418 // privatization scope, so the initialization here disregards the fact
4419 // the original variable is a reference.
4420 QualType AddrQTy =
4421 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4422 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4423 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4424 setAddrOfLocalVar(InitVD, InitAddr);
4425
4426 // Emit private declaration, it will be initialized by the value we
4427 // declaration we just added to the local declarations map.
4428 EmitDecl(*PvtVD);
4429
4430 // The initialization variables reached its purpose in the emission
4431 // ofthe previous declaration, so we don't need it anymore.
4432 LocalDeclMap.erase(InitVD);
4433
4434 // Return the address of the private variable.
4435 return GetAddrOfLocalVar(PvtVD);
4436 });
4437 assert(IsRegistered && "firstprivate var already registered as private");
4438 // Silence the warning about unused variable.
4439 (void)IsRegistered;
4440
4441 ++OrigVarIt;
4442 ++InitIt;
4443 }
4444}
4445
Michael Wong65f367f2015-07-21 13:44:28 +00004446// Generate the instructions for '#pragma omp target data' directive.
4447void CodeGenFunction::EmitOMPTargetDataDirective(
4448 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004449 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4450
4451 // Create a pre/post action to signal the privatization of the device pointer.
4452 // This action can be replaced by the OpenMP runtime code generation to
4453 // deactivate privatization.
4454 bool PrivatizeDevicePointers = false;
4455 class DevicePointerPrivActionTy : public PrePostActionTy {
4456 bool &PrivatizeDevicePointers;
4457
4458 public:
4459 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4460 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4461 void Enter(CodeGenFunction &CGF) override {
4462 PrivatizeDevicePointers = true;
4463 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004464 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004465 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4466
4467 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004468 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004469 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004470 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004471 };
4472
4473 // Codegen that selects wheather to generate the privatization code or not.
4474 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4475 &InnermostCodeGen](CodeGenFunction &CGF,
4476 PrePostActionTy &Action) {
4477 RegionCodeGenTy RCG(InnermostCodeGen);
4478 PrivatizeDevicePointers = false;
4479
4480 // Call the pre-action to change the status of PrivatizeDevicePointers if
4481 // needed.
4482 Action.Enter(CGF);
4483
4484 if (PrivatizeDevicePointers) {
4485 OMPPrivateScope PrivateScope(CGF);
4486 // Emit all instances of the use_device_ptr clause.
4487 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4488 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4489 Info.CaptureDeviceAddrMap);
4490 (void)PrivateScope.Privatize();
4491 RCG(CGF);
4492 } else
4493 RCG(CGF);
4494 };
4495
4496 // Forward the provided action to the privatization codegen.
4497 RegionCodeGenTy PrivRCG(PrivCodeGen);
4498 PrivRCG.setAction(Action);
4499
4500 // Notwithstanding the body of the region is emitted as inlined directive,
4501 // we don't use an inline scope as changes in the references inside the
4502 // region are expected to be visible outside, so we do not privative them.
4503 OMPLexicalScope Scope(CGF, S);
4504 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4505 PrivRCG);
4506 };
4507
4508 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004509
4510 // If we don't have target devices, don't bother emitting the data mapping
4511 // code.
4512 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004513 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004514 return;
4515 }
4516
4517 // Check if we have any if clause associated with the directive.
4518 const Expr *IfCond = nullptr;
4519 if (auto *C = S.getSingleClause<OMPIfClause>())
4520 IfCond = C->getCondition();
4521
4522 // Check if we have any device clause associated with the directive.
4523 const Expr *Device = nullptr;
4524 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4525 Device = C->getDevice();
4526
Samuel Antaocc10b852016-07-28 14:23:26 +00004527 // Set the action to signal privatization of device pointers.
4528 RCG.setAction(PrivAction);
4529
4530 // Emit region code.
4531 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4532 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004533}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004534
Samuel Antaodf67fc42016-01-19 19:15:56 +00004535void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4536 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004537 // If we don't have target devices, don't bother emitting the data mapping
4538 // code.
4539 if (CGM.getLangOpts().OMPTargetTriples.empty())
4540 return;
4541
4542 // Check if we have any if clause associated with the directive.
4543 const Expr *IfCond = nullptr;
4544 if (auto *C = S.getSingleClause<OMPIfClause>())
4545 IfCond = C->getCondition();
4546
4547 // Check if we have any device clause associated with the directive.
4548 const Expr *Device = nullptr;
4549 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4550 Device = C->getDevice();
4551
Alexey Bataev475a7442018-01-12 19:39:11 +00004552 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004553 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004554}
4555
Samuel Antao72590762016-01-19 20:04:50 +00004556void CodeGenFunction::EmitOMPTargetExitDataDirective(
4557 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004558 // If we don't have target devices, don't bother emitting the data mapping
4559 // code.
4560 if (CGM.getLangOpts().OMPTargetTriples.empty())
4561 return;
4562
4563 // Check if we have any if clause associated with the directive.
4564 const Expr *IfCond = nullptr;
4565 if (auto *C = S.getSingleClause<OMPIfClause>())
4566 IfCond = C->getCondition();
4567
4568 // Check if we have any device clause associated with the directive.
4569 const Expr *Device = nullptr;
4570 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4571 Device = C->getDevice();
4572
Alexey Bataev475a7442018-01-12 19:39:11 +00004573 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004574 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004575}
4576
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004577static void emitTargetParallelRegion(CodeGenFunction &CGF,
4578 const OMPTargetParallelDirective &S,
4579 PrePostActionTy &Action) {
4580 // Get the captured statement associated with the 'parallel' region.
4581 auto *CS = S.getCapturedStmt(OMPD_parallel);
4582 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004583 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4584 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4585 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4586 CGF.EmitOMPPrivateClause(S, PrivateScope);
4587 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4588 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004589 // TODO: Add support for clauses.
4590 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004591 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004592 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004593 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4594 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004595 emitPostUpdateForReductionClause(
4596 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004597}
4598
4599void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4600 CodeGenModule &CGM, StringRef ParentName,
4601 const OMPTargetParallelDirective &S) {
4602 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4603 emitTargetParallelRegion(CGF, S, Action);
4604 };
4605 llvm::Function *Fn;
4606 llvm::Constant *Addr;
4607 // Emit target region as a standalone region.
4608 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4609 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4610 assert(Fn && Addr && "Target device function emission failed.");
4611}
4612
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004613void CodeGenFunction::EmitOMPTargetParallelDirective(
4614 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004615 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4616 emitTargetParallelRegion(CGF, S, Action);
4617 };
4618 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004619}
4620
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004621static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4622 const OMPTargetParallelForDirective &S,
4623 PrePostActionTy &Action) {
4624 Action.Enter(CGF);
4625 // Emit directive as a combined directive that consists of two implicit
4626 // directives: 'parallel' with 'for' directive.
4627 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004628 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4629 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004630 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4631 emitDispatchForLoopBounds);
4632 };
4633 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4634 emitEmptyBoundParameters);
4635}
4636
4637void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4638 CodeGenModule &CGM, StringRef ParentName,
4639 const OMPTargetParallelForDirective &S) {
4640 // Emit SPMD target parallel for region as a standalone region.
4641 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4642 emitTargetParallelForRegion(CGF, S, Action);
4643 };
4644 llvm::Function *Fn;
4645 llvm::Constant *Addr;
4646 // Emit target region as a standalone region.
4647 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4648 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4649 assert(Fn && Addr && "Target device function emission failed.");
4650}
4651
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004652void CodeGenFunction::EmitOMPTargetParallelForDirective(
4653 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004654 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4655 emitTargetParallelForRegion(CGF, S, Action);
4656 };
4657 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004658}
4659
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004660static void
4661emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4662 const OMPTargetParallelForSimdDirective &S,
4663 PrePostActionTy &Action) {
4664 Action.Enter(CGF);
4665 // Emit directive as a combined directive that consists of two implicit
4666 // directives: 'parallel' with 'for' directive.
4667 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4668 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4669 emitDispatchForLoopBounds);
4670 };
4671 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4672 emitEmptyBoundParameters);
4673}
4674
4675void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4676 CodeGenModule &CGM, StringRef ParentName,
4677 const OMPTargetParallelForSimdDirective &S) {
4678 // Emit SPMD target parallel for region as a standalone region.
4679 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4680 emitTargetParallelForSimdRegion(CGF, S, Action);
4681 };
4682 llvm::Function *Fn;
4683 llvm::Constant *Addr;
4684 // Emit target region as a standalone region.
4685 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4686 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4687 assert(Fn && Addr && "Target device function emission failed.");
4688}
4689
4690void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4691 const OMPTargetParallelForSimdDirective &S) {
4692 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4693 emitTargetParallelForSimdRegion(CGF, S, Action);
4694 };
4695 emitCommonOMPTargetDirective(*this, S, CodeGen);
4696}
4697
Alexey Bataev7292c292016-04-25 12:22:29 +00004698/// Emit a helper variable and return corresponding lvalue.
4699static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4700 const ImplicitParamDecl *PVD,
4701 CodeGenFunction::OMPPrivateScope &Privates) {
4702 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4703 Privates.addPrivate(
4704 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4705}
4706
4707void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4708 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4709 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004710 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004711 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4712 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4713 const Expr *IfCond = nullptr;
4714 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4715 if (C->getNameModifier() == OMPD_unknown ||
4716 C->getNameModifier() == OMPD_taskloop) {
4717 IfCond = C->getCondition();
4718 break;
4719 }
4720 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004721
4722 OMPTaskDataTy Data;
4723 // Check if taskloop must be emitted without taskgroup.
4724 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004725 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004726 Data.Tied = true;
4727 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004728 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4729 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004730 Data.Schedule.setInt(/*IntVal=*/false);
4731 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004732 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4733 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004734 Data.Schedule.setInt(/*IntVal=*/true);
4735 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004736 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004737
4738 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4739 // if (PreCond) {
4740 // for (IV in 0..LastIteration) BODY;
4741 // <Final counter/linear vars updates>;
4742 // }
4743 //
4744
4745 // Emit: if (PreCond) - begin.
4746 // If the condition constant folds and can be elided, avoid emitting the
4747 // whole loop.
4748 bool CondConstant;
4749 llvm::BasicBlock *ContBlock = nullptr;
4750 OMPLoopScope PreInitScope(CGF, S);
4751 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4752 if (!CondConstant)
4753 return;
4754 } else {
4755 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4756 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4757 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4758 CGF.getProfileCount(&S));
4759 CGF.EmitBlock(ThenBlock);
4760 CGF.incrementProfileCounter(&S);
4761 }
4762
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004763 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4764 CGF.EmitOMPSimdInit(S);
4765
Alexey Bataev7292c292016-04-25 12:22:29 +00004766 OMPPrivateScope LoopScope(CGF);
4767 // Emit helper vars inits.
4768 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4769 auto *I = CS->getCapturedDecl()->param_begin();
4770 auto *LBP = std::next(I, LowerBound);
4771 auto *UBP = std::next(I, UpperBound);
4772 auto *STP = std::next(I, Stride);
4773 auto *LIP = std::next(I, LastIter);
4774 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4775 LoopScope);
4776 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4777 LoopScope);
4778 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4779 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4780 LoopScope);
4781 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004782 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004783 (void)LoopScope.Privatize();
4784 // Emit the loop iteration variable.
4785 const Expr *IVExpr = S.getIterationVariable();
4786 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4787 CGF.EmitVarDecl(*IVDecl);
4788 CGF.EmitIgnoredExpr(S.getInit());
4789
4790 // Emit the iterations count variable.
4791 // If it is not a variable, Sema decided to calculate iterations count on
4792 // each iteration (e.g., it is foldable into a constant).
4793 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4794 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4795 // Emit calculation of the iterations count.
4796 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4797 }
4798
4799 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4800 S.getInc(),
4801 [&S](CodeGenFunction &CGF) {
4802 CGF.EmitOMPLoopBody(S, JumpDest());
4803 CGF.EmitStopPoint(&S);
4804 },
4805 [](CodeGenFunction &) {});
4806 // Emit: if (PreCond) - end.
4807 if (ContBlock) {
4808 CGF.EmitBranch(ContBlock);
4809 CGF.EmitBlock(ContBlock, true);
4810 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004811 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4812 if (HasLastprivateClause) {
4813 CGF.EmitOMPLastprivateClauseFinal(
4814 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4815 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4816 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4817 (*LIP)->getType(), S.getLocStart())));
4818 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004819 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004820 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4821 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4822 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004823 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4824 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004825 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4826 OutlinedFn, SharedsTy,
4827 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004828 };
4829 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4830 CodeGen);
4831 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004832 if (Data.Nogroup) {
4833 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4834 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004835 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4836 *this,
4837 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4838 PrePostActionTy &Action) {
4839 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004840 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4841 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004842 },
4843 S.getLocStart());
4844 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004845}
4846
Alexey Bataev49f6e782015-12-01 04:18:41 +00004847void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004848 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004849}
4850
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004851void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4852 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004853 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004854}
Samuel Antao686c70c2016-05-26 17:30:50 +00004855
4856// Generate the instructions for '#pragma omp target update' directive.
4857void CodeGenFunction::EmitOMPTargetUpdateDirective(
4858 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004859 // If we don't have target devices, don't bother emitting the data mapping
4860 // code.
4861 if (CGM.getLangOpts().OMPTargetTriples.empty())
4862 return;
4863
4864 // Check if we have any if clause associated with the directive.
4865 const Expr *IfCond = nullptr;
4866 if (auto *C = S.getSingleClause<OMPIfClause>())
4867 IfCond = C->getCondition();
4868
4869 // Check if we have any device clause associated with the directive.
4870 const Expr *Device = nullptr;
4871 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4872 Device = C->getDevice();
4873
Alexey Bataev475a7442018-01-12 19:39:11 +00004874 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004875 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004876}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004877
4878void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4879 const OMPExecutableDirective &D) {
4880 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4881 return;
4882 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4883 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4884 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4885 } else {
4886 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4887 for (const auto *E : LD->counters()) {
4888 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4889 cast<DeclRefExpr>(E)->getDecl())) {
4890 // Emit only those that were not explicitly referenced in clauses.
4891 if (!CGF.LocalDeclMap.count(VD))
4892 CGF.EmitVarDecl(*VD);
4893 }
4894 }
4895 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004896 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004897 }
4898 };
4899 OMPSimdLexicalScope Scope(*this, D);
4900 CGM.getOpenMPRuntime().emitInlinedDirective(
4901 *this,
4902 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4903 : D.getDirectiveKind(),
4904 CodeGen);
4905}