blob: 052ebcaf389eb513e7b91fa7337ed605243f3cc3 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
69 for (auto &C : CS->captures()) {
70 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
75 const_cast<VarDecl *>(VD),
76 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000078 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000079 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80 return CGF.EmitLValue(&DRE).getAddress();
81 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000123 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
126 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
127 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
128 });
129 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000130 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000131 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
132 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
133 for (const auto *I : PreInits->decls())
134 CGF.EmitVarDecl(cast<VarDecl>(*I));
135 }
136 }
137 }
138
139public:
140 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
141 : CodeGenFunction::RunCleanupsScope(CGF) {
142 emitPreInitStmt(CGF, S);
143 }
144};
145
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000146class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
147 CodeGenFunction::OMPPrivateScope InlinedShareds;
148
149 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
150 return CGF.LambdaCaptureFields.lookup(VD) ||
151 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
152 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
153 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
154 }
155
156public:
157 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
159 InlinedShareds(CGF) {
160 for (const auto *C : S.clauses()) {
161 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
162 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
163 for (const auto *I : PreInit->decls()) {
164 if (!I->hasAttr<OMPCaptureNoInitAttr>())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
166 else {
167 CodeGenFunction::AutoVarEmission Emission =
168 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
169 CGF.EmitAutoVarCleanups(Emission);
170 }
171 }
172 }
173 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
174 for (const Expr *E : UDP->varlists()) {
175 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
176 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
177 CGF.EmitVarDecl(*OED);
178 }
179 }
180 }
181 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
182 CGF.EmitOMPPrivateClause(S, InlinedShareds);
183 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
184 if (const Expr *E = TG->getReductionRef())
185 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
186 }
187 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
188 while (CS) {
189 for (auto &C : CS->captures()) {
190 if (C.capturesVariable() || C.capturesVariableByCopy()) {
191 auto *VD = C.getCapturedVar();
192 assert(VD == VD->getCanonicalDecl() &&
193 "Canonical decl must be captured.");
194 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
195 isCapturedVar(CGF, VD) ||
196 (CGF.CapturedStmtInfo &&
197 InlinedShareds.isGlobalVarCaptured(VD)),
198 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000199 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000200 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
201 return CGF.EmitLValue(&DRE).getAddress();
202 });
203 }
204 }
205 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
206 }
207 (void)InlinedShareds.Privatize();
208 }
209};
210
Alexey Bataev3392d762016-02-16 11:18:12 +0000211} // namespace
212
Alexey Bataevf8365372017-11-17 17:57:25 +0000213static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
214 const OMPExecutableDirective &S,
215 const RegionCodeGenTy &CodeGen);
216
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000217LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
218 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
220 OrigVD = OrigVD->getCanonicalDecl();
221 bool IsCaptured =
222 LambdaCaptureFields.lookup(OrigVD) ||
223 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
224 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
226 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
227 return EmitLValue(&DRE);
228 }
229 }
230 return EmitLValue(E);
231}
232
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
234 auto &C = getContext();
235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
239 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +0000240 auto VlaSize = getVLASize(VAT);
241 Ty = VlaSize.Type;
242 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
243 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000244 }
245 SizeInChars = C.getTypeSizeInChars(Ty);
246 if (SizeInChars.isZero())
247 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
248 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
249 } else
250 Size = CGM.getSize(SizeInChars);
251 return Size;
252}
253
Alexey Bataev2377fe92015-09-10 08:12:02 +0000254void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000255 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000256 const RecordDecl *RD = S.getCapturedRecordDecl();
257 auto CurField = RD->field_begin();
258 auto CurCap = S.captures().begin();
259 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
260 E = S.capture_init_end();
261 I != E; ++I, ++CurField, ++CurCap) {
262 if (CurField->hasCapturedVLAType()) {
263 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000264 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000265 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000266 } else if (CurCap->capturesThis())
267 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000268 else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000269 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000270
271 // If the field is not a pointer, we need to save the actual value
272 // and load it as a void pointer.
273 if (!CurField->getType()->isAnyPointerType()) {
274 auto &Ctx = getContext();
275 auto DstAddr = CreateMemTemp(
276 Ctx.getUIntPtrType(),
277 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
278 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
279
280 auto *SrcAddrVal = EmitScalarConversion(
281 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000282 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000283 LValue SrcLV =
284 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
285
286 // Store the value using the source type pointer.
287 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
288
289 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000290 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000291 }
292 CapturedVars.push_back(CV);
293 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000296 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 }
298}
299
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000300static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
301 QualType DstType, StringRef Name,
302 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000303 bool isReferenceType = false) {
304 ASTContext &Ctx = CGF.getContext();
305
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000306 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
307 Ctx.getUIntPtrType(),
308 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000309 auto TmpAddr =
310 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
311 .getAddress();
312
313 // If we are dealing with references we need to return the address of the
314 // reference instead of the reference of the value.
315 if (isReferenceType) {
316 QualType RefType = Ctx.getLValueReferenceType(DstType);
317 auto *RefVal = TmpAddr.getPointer();
318 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
319 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000320 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000321 }
322
323 return TmpAddr;
324}
325
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000326static QualType getCanonicalParamType(ASTContext &C, QualType T) {
327 if (T->isLValueReferenceType()) {
328 return C.getLValueReferenceType(
329 getCanonicalParamType(C, T.getNonReferenceType()),
330 /*SpelledAsLValue=*/false);
331 }
332 if (T->isPointerType())
333 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000334 if (auto *A = T->getAsArrayTypeUnsafe()) {
335 if (auto *VLA = dyn_cast<VariableArrayType>(A))
336 return getCanonicalParamType(C, VLA->getElementType());
337 else if (!A->isVariablyModifiedType())
338 return C.getCanonicalType(T);
339 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000340 return C.getCanonicalParamType(T);
341}
342
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343namespace {
344 /// Contains required data for proper outlined function codegen.
345 struct FunctionOptions {
346 /// Captured statement for which the function is generated.
347 const CapturedStmt *S = nullptr;
348 /// true if cast to/from UIntPtr is required for variables captured by
349 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000350 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000351 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000355 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000356 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
357 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000358 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000359 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
360 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000361 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000362 };
363}
364
Alexey Bataeve754b182017-08-09 19:38:53 +0000365static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000367 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000368 &LocalAddrs,
369 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
370 &VLASizes,
371 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
372 const CapturedDecl *CD = FO.S->getCapturedDecl();
373 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 assert(CD->hasBody() && "missing CapturedDecl body");
375
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000378 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000380 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000381 Args.append(CD->param_begin(),
382 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000383 TargetArgs.append(
384 CD->param_begin(),
385 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000387 FunctionDecl *DebugFunctionDecl = nullptr;
388 if (!FO.UIntPtrCastRequired) {
389 FunctionProtoType::ExtProtoInfo EPI;
390 DebugFunctionDecl = FunctionDecl::Create(
391 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
392 SourceLocation(), DeclarationName(), Ctx.VoidTy,
393 Ctx.getTrivialTypeSourceInfo(
394 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
395 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
396 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 for (auto *FD : RD->fields()) {
398 QualType ArgType = FD->getType();
399 IdentifierInfo *II = nullptr;
400 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000401
402 // If this is a capture by copy and the type is not a pointer, the outlined
403 // function argument type should be uintptr and the value properly casted to
404 // uintptr. This is necessary given that the runtime library is only able to
405 // deal with pointers. We can pass in the same way the VLA type sizes to the
406 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000407 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000409 if (FO.UIntPtrCastRequired)
410 ArgType = Ctx.getUIntPtrType();
411 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000412
413 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000414 CapVar = I->getCapturedVar();
415 II = CapVar->getIdentifier();
416 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 else {
419 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000420 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000421 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000422 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000423 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000424 VarDecl *Arg;
425 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
426 Arg = ParmVarDecl::Create(
427 Ctx, DebugFunctionDecl,
428 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
429 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
430 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
431 } else {
432 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
433 II, ArgType, ImplicitParamDecl::Other);
434 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000435 Args.emplace_back(Arg);
436 // Do not cast arguments if we emit function with non-original types.
437 TargetArgs.emplace_back(
438 FO.UIntPtrCastRequired
439 ? Arg
440 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 ++I;
442 }
443 Args.append(
444 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
445 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000446 TargetArgs.append(
447 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
448 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449
450 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000451 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000453 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
454
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000455 llvm::Function *F =
456 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
457 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
459 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000460 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000461
462 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000463 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
464 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000466 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000467 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000468 // Do not map arguments if we emit function with non-original types.
469 Address LocalAddr(Address::invalid());
470 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
471 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
472 TargetArgs[Cnt]);
473 } else {
474 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
475 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000476 // If we are capturing a pointer by copy we don't need to do anything, just
477 // use the value that we get from the arguments.
478 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000479 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000480 // If the variable is a reference we need to materialize it here.
481 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000482 Address RefAddr = CGF.CreateMemTemp(
483 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
484 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
485 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000486 LocalAddr = RefAddr;
487 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000488 if (!FO.RegisterCastedArgsOnly)
489 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000490 ++Cnt;
491 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000492 continue;
493 }
494
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000495 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
496 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000497 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000499 ArgLVal = CGF.MakeAddrLValue(
500 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
501 Args[Cnt]->getName(), ArgLVal),
502 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000503 }
Alexey Bataev1e491372018-01-23 18:44:14 +0000504 auto *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000506 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 } else if (I->capturesVariable()) {
508 auto *Var = I->getCapturedVar();
509 QualType VarTy = Var->getType();
510 Address ArgAddr = ArgLVal.getAddress();
511 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000512 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000513 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000514 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000517 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
518 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520 if (!FO.RegisterCastedArgsOnly) {
521 LocalAddrs.insert(
522 {Args[Cnt],
523 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
524 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000525 } else if (I->capturesVariableByCopy()) {
526 assert(!FD->getType()->isAnyPointerType() &&
527 "Not expecting a captured pointer.");
528 auto *Var = I->getCapturedVar();
529 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 LocalAddrs.insert(
531 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000532 {Var, FO.UIntPtrCastRequired
533 ? castValueFromUintptr(CGF, I->getLocation(),
534 FD->getType(), Args[Cnt]->getName(),
535 ArgLVal, VarTy->isReferenceType())
536 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000537 } else {
538 // If 'this' is captured, load it into CXXThisValue.
539 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000540 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000541 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000542 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000543 ++Cnt;
544 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000545 }
546
Alexey Bataeve754b182017-08-09 19:38:53 +0000547 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000548}
549
550llvm::Function *
551CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
552 assert(
553 CapturedStmtInfo &&
554 "CapturedStmtInfo should be set when generating the captured function");
555 const CapturedDecl *CD = S.getCapturedDecl();
556 // Build the argument list.
557 bool NeedWrapperFunction =
558 getDebugInfo() &&
559 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
560 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000561 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000562 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000563 SmallString<256> Buffer;
564 llvm::raw_svector_ostream Out(Buffer);
565 Out << CapturedStmtInfo->getHelperName();
566 if (NeedWrapperFunction)
567 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000568 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000569 Out.str());
570 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
571 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000572 for (const auto &LocalAddrPair : LocalAddrs) {
573 if (LocalAddrPair.second.first) {
574 setAddrOfLocalVar(LocalAddrPair.second.first,
575 LocalAddrPair.second.second);
576 }
577 }
578 for (const auto &VLASizePair : VLASizes)
579 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000580 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000581 CapturedStmtInfo->EmitBody(*this, CD->getBody());
582 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000583 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000584 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000585
Alexey Bataevefd884d2017-08-04 21:26:25 +0000586 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000587 /*RegisterCastedArgsOnly=*/true,
588 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 Args.clear();
591 LocalAddrs.clear();
592 VLASizes.clear();
593 llvm::Function *WrapperF =
594 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000595 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000596 llvm::SmallVector<llvm::Value *, 4> CallArgs;
597 for (const auto *Arg : Args) {
598 llvm::Value *CallArg;
599 auto I = LocalAddrs.find(Arg);
600 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000601 LValue LV = WrapperCGF.MakeAddrLValue(
602 I->second.second,
603 I->second.first ? I->second.first->getType() : Arg->getType(),
604 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000605 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 } else {
607 auto EI = VLASizes.find(Arg);
608 if (EI != VLASizes.end())
609 CallArg = EI->second.second;
610 else {
611 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000612 Arg->getType(),
613 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000614 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000615 }
616 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000617 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000618 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
620 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000621 WrapperCGF.FinishFunction();
622 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000623}
624
Alexey Bataev9959db52014-05-06 10:08:46 +0000625//===----------------------------------------------------------------------===//
626// OpenMP Directive Emission
627//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address DestAddr, Address SrcAddr, QualType OriginalType,
630 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000631 // Perform element-by-element initialization.
632 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000633
634 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000635 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000636 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
637 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
638
639 auto SrcBegin = SrcAddr.getPointer();
640 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
643 // The basic structure here is a while-do loop.
644 auto BodyBB = createBasicBlock("omp.arraycpy.body");
645 auto DoneBB = createBasicBlock("omp.arraycpy.done");
646 auto IsEmpty =
647 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
648 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000649
Alexey Bataev420d45b2015-04-14 05:11:24 +0000650 // Enter the loop body, making that address the current address.
651 auto EntryBB = Builder.GetInsertBlock();
652 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000653
654 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
655
656 llvm::PHINode *SrcElementPHI =
657 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
658 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
659 Address SrcElementCurrent =
660 Address(SrcElementPHI,
661 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
662
663 llvm::PHINode *DestElementPHI =
664 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
665 DestElementPHI->addIncoming(DestBegin, EntryBB);
666 Address DestElementCurrent =
667 Address(DestElementPHI,
668 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000669
Alexey Bataev420d45b2015-04-14 05:11:24 +0000670 // Emit copy.
671 CopyGen(DestElementCurrent, SrcElementCurrent);
672
673 // Shift the address forward by one element.
674 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000675 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000676 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000677 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000678 // Check whether we've reached the end.
679 auto Done =
680 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
681 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000682 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
683 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000684
685 // Done.
686 EmitBlock(DoneBB, /*IsFinished=*/true);
687}
688
John McCall7f416cc2015-09-08 08:05:57 +0000689void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
690 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 const VarDecl *SrcVD, const Expr *Copy) {
692 if (OriginalType->isArrayType()) {
693 auto *BO = dyn_cast<BinaryOperator>(Copy);
694 if (BO && BO->getOpcode() == BO_Assign) {
695 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000696 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
697 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
698 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000699 } else {
700 // For arrays with complex element types perform element by element
701 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000702 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000703 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000704 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 // Working with the single array element, so have to remap
706 // destination and source variables to corresponding array
707 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000708 CodeGenFunction::OMPPrivateScope Remap(*this);
709 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 return DestElement;
711 });
712 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000713 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000715 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000718 } else {
719 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000720 CodeGenFunction::OMPPrivateScope Remap(*this);
721 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
722 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000723 (void)Remap.Privatize();
724 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000725 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000727}
728
Alexey Bataev69c62a92015-04-15 04:52:20 +0000729bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
730 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000731 if (!HaveInsertPoint())
732 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000733 bool FirstprivateIsLastprivate = false;
734 llvm::DenseSet<const VarDecl *> Lastprivates;
735 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
736 for (const auto *D : C->varlists())
737 Lastprivates.insert(
738 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
739 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000740 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000741 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
742 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
743 // Force emission of the firstprivate copy if the directive does not emit
744 // outlined function, like omp for, omp simd, omp distribute etc.
745 bool MustEmitFirstprivateCopy =
746 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000747 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000748 auto IRef = C->varlist_begin();
749 auto InitsRef = C->inits().begin();
750 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000751 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752 bool ThisFirstprivateIsLastprivate =
753 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
754 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000755 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000756 !FD->getType()->isReferenceType()) {
757 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
758 ++IRef;
759 ++InitsRef;
760 continue;
761 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000762 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000763 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000764 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000765 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
766 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
767 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000768 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
769 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
770 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000771 LValue OriginalLVal = EmitLValue(&DRE);
772 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000773 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000774 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000775 // Emit VarDecl with copy init for arrays.
776 // Get the address of the original variable captured in current
777 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000778 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000779 auto Emission = EmitAutoVarAlloca(*VD);
780 auto *Init = VD->getInit();
781 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
782 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000783 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(),
784 Type);
785 EmitAggregateAssign(Dest, OriginalLVal, Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000786 } else {
787 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000788 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000789 [this, VDInit, Init](Address DestElement,
790 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000791 // Clean up any temporaries needed by the initialization.
792 RunCleanupsScope InitScope(*this);
793 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000794 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000795 EmitAnyExprToMem(Init, DestElement,
796 Init->getType().getQualifiers(),
797 /*IsInitializer*/ false);
798 LocalDeclMap.erase(VDInit);
799 });
800 }
801 EmitAutoVarCleanups(Emission);
802 return Emission.getAllocatedAddress();
803 });
804 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000805 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000806 // Emit private VarDecl with copy init.
807 // Remap temp VDInit variable to the address of the original
808 // variable
809 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000810 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000811 EmitDecl(*VD);
812 LocalDeclMap.erase(VDInit);
813 return GetAddrOfLocalVar(VD);
814 });
815 }
816 assert(IsRegistered &&
817 "firstprivate var already registered as private");
818 // Silence the warning about unused variable.
819 (void)IsRegistered;
820 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000821 ++IRef;
822 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000823 }
824 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000825 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000826}
827
Alexey Bataev03b340a2014-10-21 03:16:40 +0000828void CodeGenFunction::EmitOMPPrivateClause(
829 const OMPExecutableDirective &D,
830 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000831 if (!HaveInsertPoint())
832 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000833 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000834 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000835 auto IRef = C->varlist_begin();
836 for (auto IInit : C->private_copies()) {
837 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000838 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
839 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
840 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000841 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000842 // Emit private VarDecl with copy init.
843 EmitDecl(*VD);
844 return GetAddrOfLocalVar(VD);
845 });
846 assert(IsRegistered && "private var already registered as private");
847 // Silence the warning about unused variable.
848 (void)IsRegistered;
849 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000850 ++IRef;
851 }
852 }
853}
854
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000856 if (!HaveInsertPoint())
857 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000858 // threadprivate_var1 = master_threadprivate_var1;
859 // operator=(threadprivate_var2, master_threadprivate_var2);
860 // ...
861 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000862 llvm::DenseSet<const VarDecl *> CopiedVars;
863 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000864 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000865 auto IRef = C->varlist_begin();
866 auto ISrcRef = C->source_exprs().begin();
867 auto IDestRef = C->destination_exprs().begin();
868 for (auto *AssignOp : C->assignment_ops()) {
869 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000870 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000871 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000872 // Get the address of the master variable. If we are emitting code with
873 // TLS support, the address is passed from the master as field in the
874 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000875 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000876 if (getLangOpts().OpenMPUseTLS &&
877 getContext().getTargetInfo().isTLSSupported()) {
878 assert(CapturedStmtInfo->lookup(VD) &&
879 "Copyin threadprivates should have been captured!");
880 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
881 VK_LValue, (*IRef)->getExprLoc());
882 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000883 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000884 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000885 MasterAddr =
886 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
887 : CGM.GetAddrOfGlobal(VD),
888 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000889 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000890 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000891 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000892 if (CopiedVars.size() == 1) {
893 // At first check if current thread is a master thread. If it is, no
894 // need to copy data.
895 CopyBegin = createBasicBlock("copyin.not.master");
896 CopyEnd = createBasicBlock("copyin.not.master.end");
897 Builder.CreateCondBr(
898 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000899 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
900 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000901 CopyBegin, CopyEnd);
902 EmitBlock(CopyBegin);
903 }
904 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
905 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000906 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000907 }
908 ++IRef;
909 ++ISrcRef;
910 ++IDestRef;
911 }
912 }
913 if (CopyEnd) {
914 // Exit out of copying procedure for non-master thread.
915 EmitBlock(CopyEnd, /*IsFinished=*/true);
916 return true;
917 }
918 return false;
919}
920
Alexey Bataev38e89532015-04-16 04:54:05 +0000921bool CodeGenFunction::EmitOMPLastprivateClauseInit(
922 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000923 if (!HaveInsertPoint())
924 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000925 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000926 llvm::DenseSet<const VarDecl *> SIMDLCVs;
927 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
928 auto *LoopDirective = cast<OMPLoopDirective>(&D);
929 for (auto *C : LoopDirective->counters()) {
930 SIMDLCVs.insert(
931 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
932 }
933 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000934 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000936 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000937 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
938 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000939 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000940 auto IRef = C->varlist_begin();
941 auto IDestRef = C->destination_exprs().begin();
942 for (auto *IInit : C->private_copies()) {
943 // Keep the address of the original variable for future update at the end
944 // of the loop.
945 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000946 // Taskloops do not require additional initialization, it is done in
947 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000948 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
949 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000950 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000951 DeclRefExpr DRE(
952 const_cast<VarDecl *>(OrigVD),
953 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
954 OrigVD) != nullptr,
955 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
956 return EmitLValue(&DRE).getAddress();
957 });
958 // Check if the variable is also a firstprivate: in this case IInit is
959 // not generated. Initialization of this variable will happen in codegen
960 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000961 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000962 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000963 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
964 // Emit private VarDecl with copy init.
965 EmitDecl(*VD);
966 return GetAddrOfLocalVar(VD);
967 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000968 assert(IsRegistered &&
969 "lastprivate var already registered as private");
970 (void)IsRegistered;
971 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000972 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000973 ++IRef;
974 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000975 }
976 }
977 return HasAtLeastOneLastprivate;
978}
979
980void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000981 const OMPExecutableDirective &D, bool NoFinals,
982 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000983 if (!HaveInsertPoint())
984 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000985 // Emit following code:
986 // if (<IsLastIterCond>) {
987 // orig_var1 = private_orig_var1;
988 // ...
989 // orig_varn = private_orig_varn;
990 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000991 llvm::BasicBlock *ThenBB = nullptr;
992 llvm::BasicBlock *DoneBB = nullptr;
993 if (IsLastIterCond) {
994 ThenBB = createBasicBlock(".omp.lastprivate.then");
995 DoneBB = createBasicBlock(".omp.lastprivate.done");
996 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
997 EmitBlock(ThenBB);
998 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000999 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1000 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001001 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001002 auto IC = LoopDirective->counters().begin();
1003 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001004 auto *D =
1005 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1006 if (NoFinals)
1007 AlreadyEmittedVars.insert(D);
1008 else
1009 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001010 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001011 }
1012 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001013 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1014 auto IRef = C->varlist_begin();
1015 auto ISrcRef = C->source_exprs().begin();
1016 auto IDestRef = C->destination_exprs().begin();
1017 for (auto *AssignOp : C->assignment_ops()) {
1018 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1019 QualType Type = PrivateVD->getType();
1020 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1021 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1022 // If lastprivate variable is a loop control variable for loop-based
1023 // directive, update its value before copyin back to original
1024 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001025 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1026 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001027 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1028 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1029 // Get the address of the original variable.
1030 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1031 // Get the address of the private variable.
1032 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1033 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1034 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001035 Address(Builder.CreateLoad(PrivateAddr),
1036 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001037 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001038 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001039 ++IRef;
1040 ++ISrcRef;
1041 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001042 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001043 if (auto *PostUpdate = C->getPostUpdateExpr())
1044 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001045 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001046 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001047 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001048}
1049
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001050void CodeGenFunction::EmitOMPReductionClauseInit(
1051 const OMPExecutableDirective &D,
1052 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001053 if (!HaveInsertPoint())
1054 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001055 SmallVector<const Expr *, 4> Shareds;
1056 SmallVector<const Expr *, 4> Privates;
1057 SmallVector<const Expr *, 4> ReductionOps;
1058 SmallVector<const Expr *, 4> LHSs;
1059 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001060 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001061 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001062 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001063 auto ILHS = C->lhs_exprs().begin();
1064 auto IRHS = C->rhs_exprs().begin();
1065 for (const auto *Ref : C->varlists()) {
1066 Shareds.emplace_back(Ref);
1067 Privates.emplace_back(*IPriv);
1068 ReductionOps.emplace_back(*IRed);
1069 LHSs.emplace_back(*ILHS);
1070 RHSs.emplace_back(*IRHS);
1071 std::advance(IPriv, 1);
1072 std::advance(IRed, 1);
1073 std::advance(ILHS, 1);
1074 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001075 }
1076 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001077 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1078 unsigned Count = 0;
1079 auto ILHS = LHSs.begin();
1080 auto IRHS = RHSs.begin();
1081 auto IPriv = Privates.begin();
1082 for (const auto *IRef : Shareds) {
1083 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1084 // Emit private VarDecl with reduction init.
1085 RedCG.emitSharedLValue(*this, Count);
1086 RedCG.emitAggregateType(*this, Count);
1087 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1088 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1089 RedCG.getSharedLValue(Count),
1090 [&Emission](CodeGenFunction &CGF) {
1091 CGF.EmitAutoVarInit(Emission);
1092 return true;
1093 });
1094 EmitAutoVarCleanups(Emission);
1095 Address BaseAddr = RedCG.adjustPrivateAddress(
1096 *this, Count, Emission.getAllocatedAddress());
1097 bool IsRegistered = PrivateScope.addPrivate(
1098 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1099 assert(IsRegistered && "private var already registered as private");
1100 // Silence the warning about unused variable.
1101 (void)IsRegistered;
1102
1103 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1104 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001105 QualType Type = PrivateVD->getType();
1106 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1107 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001108 // Store the address of the original variable associated with the LHS
1109 // implicit variable.
1110 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1111 return RedCG.getSharedLValue(Count).getAddress();
1112 });
1113 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1114 return GetAddrOfLocalVar(PrivateVD);
1115 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001116 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1117 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001118 // Store the address of the original variable associated with the LHS
1119 // implicit variable.
1120 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1121 return RedCG.getSharedLValue(Count).getAddress();
1122 });
1123 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1124 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1125 ConvertTypeForMem(RHSVD->getType()),
1126 "rhs.begin");
1127 });
1128 } else {
1129 QualType Type = PrivateVD->getType();
1130 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1131 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1132 // Store the address of the original variable associated with the LHS
1133 // implicit variable.
1134 if (IsArray) {
1135 OriginalAddr = Builder.CreateElementBitCast(
1136 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1137 }
1138 PrivateScope.addPrivate(
1139 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1140 PrivateScope.addPrivate(
1141 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1142 return IsArray
1143 ? Builder.CreateElementBitCast(
1144 GetAddrOfLocalVar(PrivateVD),
1145 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1146 : GetAddrOfLocalVar(PrivateVD);
1147 });
1148 }
1149 ++ILHS;
1150 ++IRHS;
1151 ++IPriv;
1152 ++Count;
1153 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001154}
1155
1156void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001157 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001158 if (!HaveInsertPoint())
1159 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001160 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001161 llvm::SmallVector<const Expr *, 8> LHSExprs;
1162 llvm::SmallVector<const Expr *, 8> RHSExprs;
1163 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001165 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001166 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001167 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001168 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1169 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1170 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1171 }
1172 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001173 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1174 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001175 ReductionKind == OMPD_simd;
1176 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001177 // Emit nowait reduction if nowait clause is present or directive is a
1178 // parallel directive (it always has implicit barrier).
1179 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001180 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001181 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001182 }
1183}
1184
Alexey Bataev61205072016-03-02 04:57:40 +00001185static void emitPostUpdateForReductionClause(
1186 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1187 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1188 if (!CGF.HaveInsertPoint())
1189 return;
1190 llvm::BasicBlock *DoneBB = nullptr;
1191 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1192 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1193 if (!DoneBB) {
1194 if (auto *Cond = CondGen(CGF)) {
1195 // If the first post-update expression is found, emit conditional
1196 // block if it was requested.
1197 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1198 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1199 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1200 CGF.EmitBlock(ThenBB);
1201 }
1202 }
1203 CGF.EmitIgnoredExpr(PostUpdate);
1204 }
1205 }
1206 if (DoneBB)
1207 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1208}
1209
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001210namespace {
1211/// Codegen lambda for appending distribute lower and upper bounds to outlined
1212/// parallel function. This is necessary for combined constructs such as
1213/// 'distribute parallel for'
1214typedef llvm::function_ref<void(CodeGenFunction &,
1215 const OMPExecutableDirective &,
1216 llvm::SmallVectorImpl<llvm::Value *> &)>
1217 CodeGenBoundParametersTy;
1218} // anonymous namespace
1219
1220static void emitCommonOMPParallelDirective(
1221 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1222 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1223 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001224 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1225 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1226 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001227 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001228 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001229 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1230 /*IgnoreResultAssign*/ true);
1231 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1232 CGF, NumThreads, NumThreadsClause->getLocStart());
1233 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001234 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001235 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001236 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1237 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1238 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001239 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001240 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1241 if (C->getNameModifier() == OMPD_unknown ||
1242 C->getNameModifier() == OMPD_parallel) {
1243 IfCond = C->getCondition();
1244 break;
1245 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001246 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001247
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001248 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001249 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001250 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1251 // lower and upper bounds with the pragma 'for' chunking mechanism.
1252 // The following lambda takes care of appending the lower and upper bound
1253 // parameters when necessary
1254 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001255 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001256 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001257 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001258}
1259
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001260static void emitEmptyBoundParameters(CodeGenFunction &,
1261 const OMPExecutableDirective &,
1262 llvm::SmallVectorImpl<llvm::Value *> &) {}
1263
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001266 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001268 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001269 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1270 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001271 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001272 // propagation master's thread values of threadprivate variables to local
1273 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001274 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1275 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1276 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001277 }
1278 CGF.EmitOMPPrivateClause(S, PrivateScope);
1279 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1280 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001281 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001282 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001283 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001284 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1285 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001286 emitPostUpdateForReductionClause(
1287 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001288}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001289
Alexey Bataev0f34da12015-07-02 04:17:07 +00001290void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1291 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 RunCleanupsScope BodyScope(*this);
1293 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001294 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001295 EmitIgnoredExpr(I);
1296 }
Alexander Musman3276a272015-03-21 10:12:56 +00001297 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001298 // In distribute directives only loop counters may be marked as linear, no
1299 // need to generate the code for them.
1300 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1301 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1302 for (auto *U : C->updates())
1303 EmitIgnoredExpr(U);
1304 }
Alexander Musman3276a272015-03-21 10:12:56 +00001305 }
1306
Alexander Musmana5f070a2014-10-01 06:03:56 +00001307 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001308 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001309 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001310 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001311 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001312 // The end (updates/cleanups).
1313 EmitBlock(Continue.getBlock());
1314 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001315}
1316
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001317void CodeGenFunction::EmitOMPInnerLoop(
1318 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1319 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001320 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1321 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001322 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001323
1324 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001325 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001327 const SourceRange &R = S.getSourceRange();
1328 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1329 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001330
1331 // If there are any cleanups between here and the loop-exit scope,
1332 // create a block to stage a loop exit along.
1333 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001334 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001335 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336
Alexander Musmand196ef22014-10-07 08:57:09 +00001337 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338
Alexey Bataev2df54a02015-03-12 08:53:29 +00001339 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001340 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001341 if (ExitBlock != LoopExit.getBlock()) {
1342 EmitBlock(ExitBlock);
1343 EmitBranchThroughCleanup(LoopExit);
1344 }
1345
1346 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001347 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348
1349 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001350 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001351 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1352
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001353 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001354
1355 // Emit "IV = IV + 1" and a back-edge to the condition block.
1356 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001357 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001358 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001359 BreakContinueStack.pop_back();
1360 EmitBranch(CondBlock);
1361 LoopStack.pop();
1362 // Emit the fall-through block.
1363 EmitBlock(LoopExit.getBlock());
1364}
1365
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001366bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001367 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001368 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001369 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001370 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001371 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001372 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001373 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001374 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001375 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1376 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1377 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1378 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1379 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1380 VD->getInit()->getType(), VK_LValue,
1381 VD->getInit()->getExprLoc());
1382 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1383 VD->getType()),
1384 /*capturedByInit=*/false);
1385 EmitAutoVarCleanups(Emission);
1386 } else
1387 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001388 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001389 // Emit the linear steps for the linear clauses.
1390 // If a step is not constant, it is pre-calculated before the loop.
1391 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1392 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001393 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001394 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001395 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001396 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001397 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001398 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001399}
1400
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401void CodeGenFunction::EmitOMPLinearClauseFinal(
1402 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001403 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001404 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001405 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001406 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001407 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001408 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001409 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001411 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001413 // If the first post-update expression is found, emit conditional
1414 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001415 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1416 DoneBB = createBasicBlock(".omp.linear.pu.done");
1417 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1418 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001419 }
1420 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1422 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001423 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001424 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001425 Address OrigAddr = EmitLValue(&DRE).getAddress();
1426 CodeGenFunction::OMPPrivateScope VarScope(*this);
1427 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001428 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001429 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001430 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001431 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001432 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001434 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001435 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001436 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001437}
1438
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001439static void emitAlignedClause(CodeGenFunction &CGF,
1440 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001441 if (!CGF.HaveInsertPoint())
1442 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001443 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001444 unsigned ClauseAlignment = 0;
1445 if (auto AlignmentExpr = Clause->getAlignment()) {
1446 auto AlignmentCI =
1447 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1448 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001449 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001450 for (auto E : Clause->varlists()) {
1451 unsigned Alignment = ClauseAlignment;
1452 if (Alignment == 0) {
1453 // OpenMP [2.8.1, Description]
1454 // If no optional parameter is specified, implementation-defined default
1455 // alignments for SIMD instructions on the target platforms are assumed.
1456 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001457 CGF.getContext()
1458 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1459 E->getType()->getPointeeType()))
1460 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001461 }
1462 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1463 "alignment is not power of 2");
1464 if (Alignment != 0) {
1465 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1466 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1467 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001468 }
1469 }
1470}
1471
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001472void CodeGenFunction::EmitOMPPrivateLoopCounters(
1473 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1474 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001475 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001476 auto I = S.private_counters().begin();
1477 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001478 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1479 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001480 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001481 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001482 if (!LocalDeclMap.count(PrivateVD)) {
1483 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1484 EmitAutoVarCleanups(VarEmission);
1485 }
1486 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1487 /*RefersToEnclosingVariableOrCapture=*/false,
1488 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1489 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001490 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001491 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1492 VD->hasGlobalStorage()) {
1493 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1494 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1495 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1496 E->getType(), VK_LValue, E->getExprLoc());
1497 return EmitLValue(&DRE).getAddress();
1498 });
1499 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001500 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001501 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001502}
1503
Alexey Bataev62dbb972015-04-22 11:59:37 +00001504static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1505 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1506 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001507 if (!CGF.HaveInsertPoint())
1508 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001509 {
1510 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001511 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001513 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001514 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001515 CGF.EmitIgnoredExpr(I);
1516 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001517 }
1518 // Check that loop is executed at least one time.
1519 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1520}
1521
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001522void CodeGenFunction::EmitOMPLinearClause(
1523 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1524 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001525 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001526 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1527 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1528 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1529 for (auto *C : LoopDirective->counters()) {
1530 SIMDLCVs.insert(
1531 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1532 }
1533 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001534 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001535 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001536 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001537 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1538 auto *PrivateVD =
1539 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001540 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1541 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1542 // Emit private VarDecl with copy init.
1543 EmitVarDecl(*PrivateVD);
1544 return GetAddrOfLocalVar(PrivateVD);
1545 });
1546 assert(IsRegistered && "linear var already registered as private");
1547 // Silence the warning about unused variable.
1548 (void)IsRegistered;
1549 } else
1550 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001551 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001552 }
1553 }
1554}
1555
Alexey Bataev45bfad52015-08-21 12:19:04 +00001556static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001557 const OMPExecutableDirective &D,
1558 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001559 if (!CGF.HaveInsertPoint())
1560 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001561 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001562 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1563 /*ignoreResult=*/true);
1564 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1565 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1566 // In presence of finite 'safelen', it may be unsafe to mark all
1567 // the memory instructions parallel, because loop-carried
1568 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001569 if (!IsMonotonic)
1570 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001571 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001572 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1573 /*ignoreResult=*/true);
1574 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001575 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001576 // In presence of finite 'safelen', it may be unsafe to mark all
1577 // the memory instructions parallel, because loop-carried
1578 // dependences of 'safelen' iterations are possible.
1579 CGF.LoopStack.setParallel(false);
1580 }
1581}
1582
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001583void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1584 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001585 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001586 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001587 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001588 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001589}
1590
Alexey Bataevef549a82016-03-09 09:49:09 +00001591void CodeGenFunction::EmitOMPSimdFinal(
1592 const OMPLoopDirective &D,
1593 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001594 if (!HaveInsertPoint())
1595 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001596 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001597 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001598 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001599 for (auto F : D.finals()) {
1600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001601 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1602 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1603 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1604 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001605 if (!DoneBB) {
1606 if (auto *Cond = CondGen(*this)) {
1607 // If the first post-update expression is found, emit conditional
1608 // block if it was requested.
1609 auto *ThenBB = createBasicBlock(".omp.final.then");
1610 DoneBB = createBasicBlock(".omp.final.done");
1611 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1612 EmitBlock(ThenBB);
1613 }
1614 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001615 Address OrigAddr = Address::invalid();
1616 if (CED)
1617 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1618 else {
1619 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1620 /*RefersToEnclosingVariableOrCapture=*/false,
1621 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1622 OrigAddr = EmitLValue(&DRE).getAddress();
1623 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001624 OMPPrivateScope VarScope(*this);
1625 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001626 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001627 (void)VarScope.Privatize();
1628 EmitIgnoredExpr(F);
1629 }
1630 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001631 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001633 if (DoneBB)
1634 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001635}
1636
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001637static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1638 const OMPLoopDirective &S,
1639 CodeGenFunction::JumpDest LoopExit) {
1640 CGF.EmitOMPLoopBody(S, LoopExit);
1641 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001642}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001643
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001644/// Emit a helper variable and return corresponding lvalue.
1645static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1646 const DeclRefExpr *Helper) {
1647 auto VDecl = cast<VarDecl>(Helper->getDecl());
1648 CGF.EmitVarDecl(*VDecl);
1649 return CGF.EmitLValue(Helper);
1650}
1651
Alexey Bataevf8365372017-11-17 17:57:25 +00001652static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1653 PrePostActionTy &Action) {
1654 Action.Enter(CGF);
1655 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1656 "Expected simd directive");
1657 OMPLoopScope PreInitScope(CGF, S);
1658 // if (PreCond) {
1659 // for (IV in 0..LastIteration) BODY;
1660 // <Final counter/linear vars updates>;
1661 // }
1662 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001663 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1664 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1665 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1666 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1667 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1668 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001669
Alexey Bataevf8365372017-11-17 17:57:25 +00001670 // Emit: if (PreCond) - begin.
1671 // If the condition constant folds and can be elided, avoid emitting the
1672 // whole loop.
1673 bool CondConstant;
1674 llvm::BasicBlock *ContBlock = nullptr;
1675 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1676 if (!CondConstant)
1677 return;
1678 } else {
1679 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1680 ContBlock = CGF.createBasicBlock("simd.if.end");
1681 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1682 CGF.getProfileCount(&S));
1683 CGF.EmitBlock(ThenBlock);
1684 CGF.incrementProfileCounter(&S);
1685 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001686
Alexey Bataevf8365372017-11-17 17:57:25 +00001687 // Emit the loop iteration variable.
1688 const Expr *IVExpr = S.getIterationVariable();
1689 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1690 CGF.EmitVarDecl(*IVDecl);
1691 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001692
Alexey Bataevf8365372017-11-17 17:57:25 +00001693 // Emit the iterations count variable.
1694 // If it is not a variable, Sema decided to calculate iterations count on
1695 // each iteration (e.g., it is foldable into a constant).
1696 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1697 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1698 // Emit calculation of the iterations count.
1699 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1700 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001701
Alexey Bataevf8365372017-11-17 17:57:25 +00001702 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001703
Alexey Bataevf8365372017-11-17 17:57:25 +00001704 emitAlignedClause(CGF, S);
1705 (void)CGF.EmitOMPLinearClauseInit(S);
1706 {
1707 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1708 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1709 CGF.EmitOMPLinearClause(S, LoopScope);
1710 CGF.EmitOMPPrivateClause(S, LoopScope);
1711 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1712 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1713 (void)LoopScope.Privatize();
1714 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1715 S.getInc(),
1716 [&S](CodeGenFunction &CGF) {
1717 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1718 CGF.EmitStopPoint(&S);
1719 },
1720 [](CodeGenFunction &) {});
1721 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001722 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001723 // Emit final copy of the lastprivate variables at the end of loops.
1724 if (HasLastprivateClause)
1725 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1726 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1727 emitPostUpdateForReductionClause(
1728 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1729 }
1730 CGF.EmitOMPLinearClauseFinal(
1731 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1732 // Emit: if (PreCond) - end.
1733 if (ContBlock) {
1734 CGF.EmitBranch(ContBlock);
1735 CGF.EmitBlock(ContBlock, true);
1736 }
1737}
1738
1739void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1740 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1741 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001742 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001743 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001744 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001745}
1746
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001747void CodeGenFunction::EmitOMPOuterLoop(
1748 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1749 CodeGenFunction::OMPPrivateScope &LoopScope,
1750 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1751 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1752 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001753 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001754
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001755 const Expr *IVExpr = S.getIterationVariable();
1756 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1757 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1758
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001759 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1760
1761 // Start the loop with a block that tests the condition.
1762 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1763 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001764 const SourceRange &R = S.getSourceRange();
1765 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1766 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001767
1768 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001769 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001770 // UB = min(UB, GlobalUB) or
1771 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1772 // 'distribute parallel for')
1773 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001774 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001775 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001777 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001778 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001779 BoolCondVal =
1780 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1781 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001782 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001783
1784 // If there are any cleanups between here and the loop-exit scope,
1785 // create a block to stage a loop exit along.
1786 auto ExitBlock = LoopExit.getBlock();
1787 if (LoopScope.requiresCleanups())
1788 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1789
1790 auto LoopBody = createBasicBlock("omp.dispatch.body");
1791 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1792 if (ExitBlock != LoopExit.getBlock()) {
1793 EmitBlock(ExitBlock);
1794 EmitBranchThroughCleanup(LoopExit);
1795 }
1796 EmitBlock(LoopBody);
1797
Alexander Musman92bdaab2015-03-12 13:37:50 +00001798 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1799 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001800 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001801 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001802
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001803 // Create a block for the increment.
1804 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1805 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1806
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001807 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1808 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001809 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1810 LoopStack.setParallel(!IsMonotonic);
1811 else
1812 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001813
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001814 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001815
1816 // when 'distribute' is not combined with a 'for':
1817 // while (idx <= UB) { BODY; ++idx; }
1818 // when 'distribute' is combined with a 'for'
1819 // (e.g. 'distribute parallel for')
1820 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1821 EmitOMPInnerLoop(
1822 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1823 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1824 CodeGenLoop(CGF, S, LoopExit);
1825 },
1826 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1827 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1828 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001829
1830 EmitBlock(Continue.getBlock());
1831 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001832 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001833 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001834 EmitIgnoredExpr(LoopArgs.NextLB);
1835 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001836 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001837
1838 EmitBranch(CondBlock);
1839 LoopStack.pop();
1840 // Emit the fall-through block.
1841 EmitBlock(LoopExit.getBlock());
1842
1843 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001844 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1845 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001846 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1847 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001848 };
1849 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001850}
1851
1852void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001853 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001854 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001855 const OMPLoopArguments &LoopArgs,
1856 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001857 auto &RT = CGM.getOpenMPRuntime();
1858
1859 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001860 const bool DynamicOrOrdered =
1861 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001862
1863 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001864 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001865 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001866 "static non-chunked schedule does not need outer loop");
1867
1868 // Emit outer loop.
1869 //
1870 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1871 // When schedule(dynamic,chunk_size) is specified, the iterations are
1872 // distributed to threads in the team in chunks as the threads request them.
1873 // Each thread executes a chunk of iterations, then requests another chunk,
1874 // until no chunks remain to be distributed. Each chunk contains chunk_size
1875 // iterations, except for the last chunk to be distributed, which may have
1876 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1877 //
1878 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1879 // to threads in the team in chunks as the executing threads request them.
1880 // Each thread executes a chunk of iterations, then requests another chunk,
1881 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1882 // each chunk is proportional to the number of unassigned iterations divided
1883 // by the number of threads in the team, decreasing to 1. For a chunk_size
1884 // with value k (greater than 1), the size of each chunk is determined in the
1885 // same way, with the restriction that the chunks do not contain fewer than k
1886 // iterations (except for the last chunk to be assigned, which may have fewer
1887 // than k iterations).
1888 //
1889 // When schedule(auto) is specified, the decision regarding scheduling is
1890 // delegated to the compiler and/or runtime system. The programmer gives the
1891 // implementation the freedom to choose any possible mapping of iterations to
1892 // threads in the team.
1893 //
1894 // When schedule(runtime) is specified, the decision regarding scheduling is
1895 // deferred until run time, and the schedule and chunk size are taken from the
1896 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1897 // implementation defined
1898 //
1899 // while(__kmpc_dispatch_next(&LB, &UB)) {
1900 // idx = LB;
1901 // while (idx <= UB) { BODY; ++idx;
1902 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1903 // } // inner loop
1904 // }
1905 //
1906 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1907 // When schedule(static, chunk_size) is specified, iterations are divided into
1908 // chunks of size chunk_size, and the chunks are assigned to the threads in
1909 // the team in a round-robin fashion in the order of the thread number.
1910 //
1911 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1912 // while (idx <= UB) { BODY; ++idx; } // inner loop
1913 // LB = LB + ST;
1914 // UB = UB + ST;
1915 // }
1916 //
1917
1918 const Expr *IVExpr = S.getIterationVariable();
1919 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1920 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1921
1922 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001923 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1924 llvm::Value *LBVal = DispatchBounds.first;
1925 llvm::Value *UBVal = DispatchBounds.second;
1926 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1927 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001928 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001929 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001930 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001931 CGOpenMPRuntime::StaticRTInput StaticInit(
1932 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1933 LoopArgs.ST, LoopArgs.Chunk);
1934 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1935 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001936 }
1937
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001938 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1939 const unsigned IVSize,
1940 const bool IVSigned) {
1941 if (Ordered) {
1942 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1943 IVSigned);
1944 }
1945 };
1946
1947 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1948 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1949 OuterLoopArgs.IncExpr = S.getInc();
1950 OuterLoopArgs.Init = S.getInit();
1951 OuterLoopArgs.Cond = S.getCond();
1952 OuterLoopArgs.NextLB = S.getNextLowerBound();
1953 OuterLoopArgs.NextUB = S.getNextUpperBound();
1954 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1955 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001956}
1957
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001958static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1959 const unsigned IVSize, const bool IVSigned) {}
1960
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001961void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001962 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1963 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1964 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001965
1966 auto &RT = CGM.getOpenMPRuntime();
1967
1968 // Emit outer loop.
1969 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1970 // dynamic
1971 //
1972
1973 const Expr *IVExpr = S.getIterationVariable();
1974 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1975 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1976
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001977 CGOpenMPRuntime::StaticRTInput StaticInit(
1978 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1979 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1980 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001981
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001982 // for combined 'distribute' and 'for' the increment expression of distribute
1983 // is store in DistInc. For 'distribute' alone, it is in Inc.
1984 Expr *IncExpr;
1985 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1986 IncExpr = S.getDistInc();
1987 else
1988 IncExpr = S.getInc();
1989
1990 // this routine is shared by 'omp distribute parallel for' and
1991 // 'omp distribute': select the right EUB expression depending on the
1992 // directive
1993 OMPLoopArguments OuterLoopArgs;
1994 OuterLoopArgs.LB = LoopArgs.LB;
1995 OuterLoopArgs.UB = LoopArgs.UB;
1996 OuterLoopArgs.ST = LoopArgs.ST;
1997 OuterLoopArgs.IL = LoopArgs.IL;
1998 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1999 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2000 ? S.getCombinedEnsureUpperBound()
2001 : S.getEnsureUpperBound();
2002 OuterLoopArgs.IncExpr = IncExpr;
2003 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2004 ? S.getCombinedInit()
2005 : S.getInit();
2006 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2007 ? S.getCombinedCond()
2008 : S.getCond();
2009 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2010 ? S.getCombinedNextLowerBound()
2011 : S.getNextLowerBound();
2012 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2013 ? S.getCombinedNextUpperBound()
2014 : S.getNextUpperBound();
2015
2016 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2017 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2018 emitEmptyOrdered);
2019}
2020
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002021static std::pair<LValue, LValue>
2022emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2023 const OMPExecutableDirective &S) {
2024 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2025 LValue LB =
2026 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2027 LValue UB =
2028 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2029
2030 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2031 // parallel for') we need to use the 'distribute'
2032 // chunk lower and upper bounds rather than the whole loop iteration
2033 // space. These are parameters to the outlined function for 'parallel'
2034 // and we copy the bounds of the previous schedule into the
2035 // the current ones.
2036 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2037 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002038 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2039 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002040 PrevLBVal = CGF.EmitScalarConversion(
2041 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002042 LS.getIterationVariable()->getType(),
2043 LS.getPrevLowerBoundVariable()->getExprLoc());
2044 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2045 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002046 PrevUBVal = CGF.EmitScalarConversion(
2047 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002048 LS.getIterationVariable()->getType(),
2049 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002050
2051 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2052 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2053
2054 return {LB, UB};
2055}
2056
2057/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2058/// we need to use the LB and UB expressions generated by the worksharing
2059/// code generation support, whereas in non combined situations we would
2060/// just emit 0 and the LastIteration expression
2061/// This function is necessary due to the difference of the LB and UB
2062/// types for the RT emission routines for 'for_static_init' and
2063/// 'for_dispatch_init'
2064static std::pair<llvm::Value *, llvm::Value *>
2065emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2066 const OMPExecutableDirective &S,
2067 Address LB, Address UB) {
2068 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2069 const Expr *IVExpr = LS.getIterationVariable();
2070 // when implementing a dynamic schedule for a 'for' combined with a
2071 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2072 // is not normalized as each team only executes its own assigned
2073 // distribute chunk
2074 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002075 llvm::Value *LBVal =
2076 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2077 llvm::Value *UBVal =
2078 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002079 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002080}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002081
2082static void emitDistributeParallelForDistributeInnerBoundParams(
2083 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2084 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2085 const auto &Dir = cast<OMPLoopDirective>(S);
2086 LValue LB =
2087 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2088 auto LBCast = CGF.Builder.CreateIntCast(
2089 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2090 CapturedVars.push_back(LBCast);
2091 LValue UB =
2092 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2093
2094 auto UBCast = CGF.Builder.CreateIntCast(
2095 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2096 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002097}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002098
2099static void
2100emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2101 const OMPLoopDirective &S,
2102 CodeGenFunction::JumpDest LoopExit) {
2103 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2104 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002105 bool HasCancel = false;
2106 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2107 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2108 HasCancel = D->hasCancel();
2109 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2110 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002111 else if (const auto *D =
2112 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2113 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002114 }
2115 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2116 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002117 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2118 emitDistributeParallelForInnerBounds,
2119 emitDistributeParallelForDispatchBounds);
2120 };
2121
2122 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002123 CGF, S,
2124 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2125 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002126 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002127}
2128
Carlo Bertolli9925f152016-06-27 14:55:37 +00002129void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2130 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002131 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2132 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2133 S.getDistInc());
2134 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002135 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002136 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002137}
2138
Kelvin Li4a39add2016-07-05 05:00:15 +00002139void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2140 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002141 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2142 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2143 S.getDistInc());
2144 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002145 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002146 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002147}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002148
2149void CodeGenFunction::EmitOMPDistributeSimdDirective(
2150 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002151 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2152 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2153 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002154 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002155 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002156}
2157
Alexey Bataevf8365372017-11-17 17:57:25 +00002158void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2159 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2160 // Emit SPMD target parallel for region as a standalone region.
2161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2162 emitOMPSimdRegion(CGF, S, Action);
2163 };
2164 llvm::Function *Fn;
2165 llvm::Constant *Addr;
2166 // Emit target region as a standalone region.
2167 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2168 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2169 assert(Fn && Addr && "Target device function emission failed.");
2170}
2171
Kelvin Li986330c2016-07-20 22:57:10 +00002172void CodeGenFunction::EmitOMPTargetSimdDirective(
2173 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002174 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2175 emitOMPSimdRegion(CGF, S, Action);
2176 };
2177 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002178}
2179
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002180namespace {
2181 struct ScheduleKindModifiersTy {
2182 OpenMPScheduleClauseKind Kind;
2183 OpenMPScheduleClauseModifier M1;
2184 OpenMPScheduleClauseModifier M2;
2185 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2186 OpenMPScheduleClauseModifier M1,
2187 OpenMPScheduleClauseModifier M2)
2188 : Kind(Kind), M1(M1), M2(M2) {}
2189 };
2190} // namespace
2191
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002192bool CodeGenFunction::EmitOMPWorksharingLoop(
2193 const OMPLoopDirective &S, Expr *EUB,
2194 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2195 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002196 // Emit the loop iteration variable.
2197 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2198 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2199 EmitVarDecl(*IVDecl);
2200
2201 // Emit the iterations count variable.
2202 // If it is not a variable, Sema decided to calculate iterations count on each
2203 // iteration (e.g., it is foldable into a constant).
2204 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2205 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2206 // Emit calculation of the iterations count.
2207 EmitIgnoredExpr(S.getCalcLastIteration());
2208 }
2209
2210 auto &RT = CGM.getOpenMPRuntime();
2211
Alexey Bataev38e89532015-04-16 04:54:05 +00002212 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002213 // Check pre-condition.
2214 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002215 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002216 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002217 // If the condition constant folds and can be elided, avoid emitting the
2218 // whole loop.
2219 bool CondConstant;
2220 llvm::BasicBlock *ContBlock = nullptr;
2221 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2222 if (!CondConstant)
2223 return false;
2224 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002225 auto *ThenBlock = createBasicBlock("omp.precond.then");
2226 ContBlock = createBasicBlock("omp.precond.end");
2227 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002228 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002229 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002230 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002231 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002232
Alexey Bataev8b427062016-05-25 12:36:08 +00002233 bool Ordered = false;
2234 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2235 if (OrderedClause->getNumForLoops())
2236 RT.emitDoacrossInit(*this, S);
2237 else
2238 Ordered = true;
2239 }
2240
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002241 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002242 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002243 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002244 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002245
2246 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2247 LValue LB = Bounds.first;
2248 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002249 LValue ST =
2250 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2251 LValue IL =
2252 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2253
Alexander Musmanc6388682014-12-15 07:07:06 +00002254 // Emit 'then' code.
2255 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002256 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002257 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002258 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002259 // initialization of firstprivate variables and post-update of
2260 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002261 CGM.getOpenMPRuntime().emitBarrierCall(
2262 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2263 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002264 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002265 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002266 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002267 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002268 EmitOMPPrivateLoopCounters(S, LoopScope);
2269 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002270 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002271
2272 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002273 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002274 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002275 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002276 ScheduleKind.Schedule = C->getScheduleKind();
2277 ScheduleKind.M1 = C->getFirstScheduleModifier();
2278 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002279 if (const auto *Ch = C->getChunkSize()) {
2280 Chunk = EmitScalarExpr(Ch);
2281 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2282 S.getIterationVariable()->getType(),
2283 S.getLocStart());
2284 }
2285 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002286 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2287 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002288 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2289 // If the static schedule kind is specified or if the ordered clause is
2290 // specified, and if no monotonic modifier is specified, the effect will
2291 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002292 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002293 /* Chunked */ Chunk != nullptr) &&
2294 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002295 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2296 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002297 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2298 // When no chunk_size is specified, the iteration space is divided into
2299 // chunks that are approximately equal in size, and at most one chunk is
2300 // distributed to each thread. Note that the size of the chunks is
2301 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002302 CGOpenMPRuntime::StaticRTInput StaticInit(
2303 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2304 UB.getAddress(), ST.getAddress());
2305 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2306 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002307 auto LoopExit =
2308 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002309 // UB = min(UB, GlobalUB);
2310 EmitIgnoredExpr(S.getEnsureUpperBound());
2311 // IV = LB;
2312 EmitIgnoredExpr(S.getInit());
2313 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002314 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2315 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002316 [&S, LoopExit](CodeGenFunction &CGF) {
2317 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002318 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002319 },
2320 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002321 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002322 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002323 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002324 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2325 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002326 };
2327 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002328 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002329 const bool IsMonotonic =
2330 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2331 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2332 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2333 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002334 // Emit the outer loop, which requests its work chunk [LB..UB] from
2335 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002336 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2337 ST.getAddress(), IL.getAddress(),
2338 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002339 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002340 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002341 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002342 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2343 EmitOMPSimdFinal(S,
2344 [&](CodeGenFunction &CGF) -> llvm::Value * {
2345 return CGF.Builder.CreateIsNotNull(
2346 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2347 });
2348 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002349 EmitOMPReductionClauseFinal(
2350 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2351 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2352 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002353 // Emit post-update of the reduction variables if IsLastIter != 0.
2354 emitPostUpdateForReductionClause(
2355 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2356 return CGF.Builder.CreateIsNotNull(
2357 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2358 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002359 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2360 if (HasLastprivateClause)
2361 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002362 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2363 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002364 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002365 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002366 return CGF.Builder.CreateIsNotNull(
2367 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2368 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002369 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002370 if (ContBlock) {
2371 EmitBranch(ContBlock);
2372 EmitBlock(ContBlock, true);
2373 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002375 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002376}
2377
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002378/// The following two functions generate expressions for the loop lower
2379/// and upper bounds in case of static and dynamic (dispatch) schedule
2380/// of the associated 'for' or 'distribute' loop.
2381static std::pair<LValue, LValue>
2382emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2383 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2384 LValue LB =
2385 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2386 LValue UB =
2387 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2388 return {LB, UB};
2389}
2390
2391/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2392/// consider the lower and upper bound expressions generated by the
2393/// worksharing loop support, but we use 0 and the iteration space size as
2394/// constants
2395static std::pair<llvm::Value *, llvm::Value *>
2396emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2397 Address LB, Address UB) {
2398 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2399 const Expr *IVExpr = LS.getIterationVariable();
2400 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2401 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2402 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2403 return {LBVal, UBVal};
2404}
2405
Alexander Musmanc6388682014-12-15 07:07:06 +00002406void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002407 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002408 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2409 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002410 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002411 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2412 emitForLoopBounds,
2413 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002414 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002415 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002416 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002417 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2418 S.hasCancel());
2419 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002420
2421 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002422 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002423 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2424 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002425}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002426
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002427void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002428 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002429 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2430 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002431 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2432 emitForLoopBounds,
2433 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002434 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002435 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002436 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002437 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2438 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002439
2440 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002441 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002442 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2443 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002444}
2445
Alexey Bataev2df54a02015-03-12 08:53:29 +00002446static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2447 const Twine &Name,
2448 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002449 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002450 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002451 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002452 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002453}
2454
Alexey Bataev3392d762016-02-16 11:18:12 +00002455void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002456 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2457 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002458 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002459 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2460 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002461 auto &C = CGF.CGM.getContext();
2462 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2463 // Emit helper vars inits.
2464 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2465 CGF.Builder.getInt32(0));
2466 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2467 : CGF.Builder.getInt32(0);
2468 LValue UB =
2469 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2470 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2471 CGF.Builder.getInt32(1));
2472 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2473 CGF.Builder.getInt32(0));
2474 // Loop counter.
2475 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2476 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2477 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2478 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2479 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2480 // Generate condition for loop.
2481 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002482 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 // Increment for loop counter.
2484 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002485 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002486 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2487 // Iterate through all sections and emit a switch construct:
2488 // switch (IV) {
2489 // case 0:
2490 // <SectionStmt[0]>;
2491 // break;
2492 // ...
2493 // case <NumSection> - 1:
2494 // <SectionStmt[<NumSection> - 1]>;
2495 // break;
2496 // }
2497 // .omp.sections.exit:
2498 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002499 auto *SwitchStmt =
2500 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2501 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002502 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002503 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002504 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002505 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2506 CGF.EmitBlock(CaseBB);
2507 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002508 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002509 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002510 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002511 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002512 } else {
2513 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2514 CGF.EmitBlock(CaseBB);
2515 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2516 CGF.EmitStmt(Stmt);
2517 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002518 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002519 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002520 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002521
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002522 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2523 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002524 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002525 // initialization of firstprivate variables and post-update of lastprivate
2526 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002527 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2528 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2529 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002530 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002531 CGF.EmitOMPPrivateClause(S, LoopScope);
2532 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2533 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2534 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002535
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002536 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002537 OpenMPScheduleTy ScheduleKind;
2538 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002539 CGOpenMPRuntime::StaticRTInput StaticInit(
2540 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2541 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002542 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002543 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002544 // UB = min(UB, GlobalUB);
2545 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2546 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2547 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2548 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2549 // IV = LB;
2550 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2551 // while (idx <= UB) { BODY; ++idx; }
2552 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2553 [](CodeGenFunction &) {});
2554 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002555 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002556 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2557 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002558 };
2559 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002560 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002561 // Emit post-update of the reduction variables if IsLastIter != 0.
2562 emitPostUpdateForReductionClause(
2563 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2564 return CGF.Builder.CreateIsNotNull(
2565 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2566 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002567
2568 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2569 if (HasLastprivates)
2570 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002571 S, /*NoFinals=*/false,
2572 CGF.Builder.CreateIsNotNull(
2573 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002574 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002575
2576 bool HasCancel = false;
2577 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2578 HasCancel = OSD->hasCancel();
2579 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2580 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002581 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002582 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2583 HasCancel);
2584 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2585 // clause. Otherwise the barrier will be generated by the codegen for the
2586 // directive.
2587 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002588 // Emit implicit barrier to synchronize threads and avoid data races on
2589 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002590 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2591 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002592 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002593}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002594
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002595void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002596 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002597 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002598 EmitSections(S);
2599 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002600 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002601 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002602 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2603 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002604 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002605}
2606
2607void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002608 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002609 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002611 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002612 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2613 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002614}
2615
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002616void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002617 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002618 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002619 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002620 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002621 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002622 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002623 // Build a list of copyprivate variables along with helper expressions
2624 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002625 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002626 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002627 DestExprs.append(C->destination_exprs().begin(),
2628 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002629 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002630 AssignmentOps.append(C->assignment_ops().begin(),
2631 C->assignment_ops().end());
2632 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002633 // Emit code for 'single' region along with 'copyprivate' clauses
2634 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2635 Action.Enter(CGF);
2636 OMPPrivateScope SingleScope(CGF);
2637 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2638 CGF.EmitOMPPrivateClause(S, SingleScope);
2639 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002640 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002641 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002642 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002643 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002644 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2645 CopyprivateVars, DestExprs,
2646 SrcExprs, AssignmentOps);
2647 }
2648 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2649 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002650 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002651 CGM.getOpenMPRuntime().emitBarrierCall(
2652 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002653 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002654 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002655}
2656
Alexey Bataev8d690652014-12-04 07:23:53 +00002657void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002658 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2659 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002660 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002662 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002663 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002664}
2665
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002666void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002667 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2668 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002669 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002670 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002671 Expr *Hint = nullptr;
2672 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2673 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002674 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002675 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2676 S.getDirectiveName().getAsString(),
2677 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002678}
2679
Alexey Bataev671605e2015-04-13 05:28:11 +00002680void CodeGenFunction::EmitOMPParallelForDirective(
2681 const OMPParallelForDirective &S) {
2682 // Emit directive as a combined directive that consists of two implicit
2683 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002684 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002685 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002686 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2687 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002688 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002689 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2690 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002691}
2692
Alexander Musmane4e893b2014-09-23 09:33:00 +00002693void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002694 const OMPParallelForSimdDirective &S) {
2695 // Emit directive as a combined directive that consists of two implicit
2696 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002697 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002698 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2699 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002700 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002701 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2702 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002703}
2704
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002705void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002706 const OMPParallelSectionsDirective &S) {
2707 // Emit directive as a combined directive that consists of two implicit
2708 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002709 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2710 CGF.EmitSections(S);
2711 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002712 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2713 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002714}
2715
Alexey Bataev475a7442018-01-12 19:39:11 +00002716void CodeGenFunction::EmitOMPTaskBasedDirective(
2717 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2718 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2719 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002720 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002721 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002722 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002723 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002724 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002725 // Check if the task is final
2726 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2727 // If the condition constant folds and can be elided, try to avoid emitting
2728 // the condition and the dead arm of the if/else.
2729 auto *Cond = Clause->getCondition();
2730 bool CondConstant;
2731 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2732 Data.Final.setInt(CondConstant);
2733 else
2734 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2735 } else {
2736 // By default the task is not final.
2737 Data.Final.setInt(/*IntVal=*/false);
2738 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002739 // Check if the task has 'priority' clause.
2740 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002741 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002742 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002743 Data.Priority.setPointer(EmitScalarConversion(
2744 EmitScalarExpr(Prio), Prio->getType(),
2745 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2746 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002747 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002748 // The first function argument for tasks is a thread id, the second one is a
2749 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002750 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2751 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002752 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002753 auto IRef = C->varlist_begin();
2754 for (auto *IInit : C->private_copies()) {
2755 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2756 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002757 Data.PrivateVars.push_back(*IRef);
2758 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002759 }
2760 ++IRef;
2761 }
2762 }
2763 EmittedAsPrivate.clear();
2764 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002765 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002766 auto IRef = C->varlist_begin();
2767 auto IElemInitRef = C->inits().begin();
2768 for (auto *IInit : C->private_copies()) {
2769 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2770 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002771 Data.FirstprivateVars.push_back(*IRef);
2772 Data.FirstprivateCopies.push_back(IInit);
2773 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002774 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002775 ++IRef;
2776 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002777 }
2778 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002779 // Get list of lastprivate variables (for taskloops).
2780 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2781 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2782 auto IRef = C->varlist_begin();
2783 auto ID = C->destination_exprs().begin();
2784 for (auto *IInit : C->private_copies()) {
2785 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2786 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2787 Data.LastprivateVars.push_back(*IRef);
2788 Data.LastprivateCopies.push_back(IInit);
2789 }
2790 LastprivateDstsOrigs.insert(
2791 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2792 cast<DeclRefExpr>(*IRef)});
2793 ++IRef;
2794 ++ID;
2795 }
2796 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002797 SmallVector<const Expr *, 4> LHSs;
2798 SmallVector<const Expr *, 4> RHSs;
2799 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2800 auto IPriv = C->privates().begin();
2801 auto IRed = C->reduction_ops().begin();
2802 auto ILHS = C->lhs_exprs().begin();
2803 auto IRHS = C->rhs_exprs().begin();
2804 for (const auto *Ref : C->varlists()) {
2805 Data.ReductionVars.emplace_back(Ref);
2806 Data.ReductionCopies.emplace_back(*IPriv);
2807 Data.ReductionOps.emplace_back(*IRed);
2808 LHSs.emplace_back(*ILHS);
2809 RHSs.emplace_back(*IRHS);
2810 std::advance(IPriv, 1);
2811 std::advance(IRed, 1);
2812 std::advance(ILHS, 1);
2813 std::advance(IRHS, 1);
2814 }
2815 }
2816 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2817 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002818 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002819 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2820 for (auto *IRef : C->varlists())
2821 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002822 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2823 CapturedRegion](CodeGenFunction &CGF,
2824 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002825 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002826 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002827 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2828 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002829 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002830 auto *CopyFn = CGF.Builder.CreateLoad(
2831 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2832 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2833 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2834 // Map privates.
2835 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2836 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2837 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002838 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002839 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2840 Address PrivatePtr = CGF.CreateMemTemp(
2841 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2842 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2843 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002844 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002845 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002846 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2847 Address PrivatePtr =
2848 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2849 ".firstpriv.ptr.addr");
2850 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2851 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002852 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002853 for (auto *E : Data.LastprivateVars) {
2854 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2855 Address PrivatePtr =
2856 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2857 ".lastpriv.ptr.addr");
2858 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2859 CallArgs.push_back(PrivatePtr.getPointer());
2860 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002861 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2862 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002863 for (auto &&Pair : LastprivateDstsOrigs) {
2864 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2865 DeclRefExpr DRE(
2866 const_cast<VarDecl *>(OrigVD),
2867 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2868 OrigVD) != nullptr,
2869 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2870 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2871 return CGF.EmitLValue(&DRE).getAddress();
2872 });
2873 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002874 for (auto &&Pair : PrivatePtrs) {
2875 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2876 CGF.getContext().getDeclAlign(Pair.first));
2877 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2878 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002879 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002880 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002881 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002882 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2883 Data.ReductionOps);
2884 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2885 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2886 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2887 RedCG.emitSharedLValue(CGF, Cnt);
2888 RedCG.emitAggregateType(CGF, Cnt);
2889 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2890 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2891 Replacement =
2892 Address(CGF.EmitScalarConversion(
2893 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2894 CGF.getContext().getPointerType(
2895 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002896 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002897 Replacement.getAlignment());
2898 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2899 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2900 [Replacement]() { return Replacement; });
2901 // FIXME: This must removed once the runtime library is fixed.
2902 // Emit required threadprivate variables for
2903 // initilizer/combiner/finalizer.
2904 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2905 RedCG, Cnt);
2906 }
2907 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002908 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002910 SmallVector<const Expr *, 4> InRedVars;
2911 SmallVector<const Expr *, 4> InRedPrivs;
2912 SmallVector<const Expr *, 4> InRedOps;
2913 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2914 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2915 auto IPriv = C->privates().begin();
2916 auto IRed = C->reduction_ops().begin();
2917 auto ITD = C->taskgroup_descriptors().begin();
2918 for (const auto *Ref : C->varlists()) {
2919 InRedVars.emplace_back(Ref);
2920 InRedPrivs.emplace_back(*IPriv);
2921 InRedOps.emplace_back(*IRed);
2922 TaskgroupDescriptors.emplace_back(*ITD);
2923 std::advance(IPriv, 1);
2924 std::advance(IRed, 1);
2925 std::advance(ITD, 1);
2926 }
2927 }
2928 // Privatize in_reduction items here, because taskgroup descriptors must be
2929 // privatized earlier.
2930 OMPPrivateScope InRedScope(CGF);
2931 if (!InRedVars.empty()) {
2932 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2933 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2934 RedCG.emitSharedLValue(CGF, Cnt);
2935 RedCG.emitAggregateType(CGF, Cnt);
2936 // The taskgroup descriptor variable is always implicit firstprivate and
2937 // privatized already during procoessing of the firstprivates.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002938 llvm::Value *ReductionsPtr =
2939 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2940 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002941 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2942 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2943 Replacement = Address(
2944 CGF.EmitScalarConversion(
2945 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2946 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002947 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002948 Replacement.getAlignment());
2949 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2950 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2951 [Replacement]() { return Replacement; });
2952 // FIXME: This must removed once the runtime library is fixed.
2953 // Emit required threadprivate variables for
2954 // initilizer/combiner/finalizer.
2955 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2956 RedCG, Cnt);
2957 }
2958 }
2959 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002960
2961 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002962 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002963 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002964 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2965 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2966 Data.NumberOfParts);
2967 OMPLexicalScope Scope(*this, S);
2968 TaskGen(*this, OutlinedFn, Data);
2969}
2970
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002971static ImplicitParamDecl *
2972createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002973 QualType Ty, CapturedDecl *CD,
2974 SourceLocation Loc) {
2975 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2976 ImplicitParamDecl::Other);
2977 auto *OrigRef = DeclRefExpr::Create(
2978 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2979 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2980 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2981 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002982 auto *PrivateRef = DeclRefExpr::Create(
2983 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002984 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002985 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002986 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2987 ImplicitParamDecl::Other);
2988 auto *InitRef = DeclRefExpr::Create(
2989 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2990 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002991 PrivateVD->setInitStyle(VarDecl::CInit);
2992 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2993 InitRef, /*BasePath=*/nullptr,
2994 VK_RValue));
2995 Data.FirstprivateVars.emplace_back(OrigRef);
2996 Data.FirstprivateCopies.emplace_back(PrivateRef);
2997 Data.FirstprivateInits.emplace_back(InitRef);
2998 return OrigVD;
2999}
3000
3001void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3002 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3003 OMPTargetDataInfo &InputInfo) {
3004 // Emit outlined function for task construct.
3005 auto CS = S.getCapturedStmt(OMPD_task);
3006 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3007 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3008 auto *I = CS->getCapturedDecl()->param_begin();
3009 auto *PartId = std::next(I);
3010 auto *TaskT = std::next(I, 4);
3011 OMPTaskDataTy Data;
3012 // The task is not final.
3013 Data.Final.setInt(/*IntVal=*/false);
3014 // Get list of firstprivate variables.
3015 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3016 auto IRef = C->varlist_begin();
3017 auto IElemInitRef = C->inits().begin();
3018 for (auto *IInit : C->private_copies()) {
3019 Data.FirstprivateVars.push_back(*IRef);
3020 Data.FirstprivateCopies.push_back(IInit);
3021 Data.FirstprivateInits.push_back(*IElemInitRef);
3022 ++IRef;
3023 ++IElemInitRef;
3024 }
3025 }
3026 OMPPrivateScope TargetScope(*this);
3027 VarDecl *BPVD = nullptr;
3028 VarDecl *PVD = nullptr;
3029 VarDecl *SVD = nullptr;
3030 if (InputInfo.NumberOfTargetItems > 0) {
3031 auto *CD = CapturedDecl::Create(
3032 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3033 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3034 QualType BaseAndPointersType = getContext().getConstantArrayType(
3035 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3036 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003037 BPVD = createImplicitFirstprivateForType(
3038 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3039 PVD = createImplicitFirstprivateForType(
3040 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003041 QualType SizesType = getContext().getConstantArrayType(
3042 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3043 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003044 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3045 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003046 TargetScope.addPrivate(
3047 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3048 TargetScope.addPrivate(PVD,
3049 [&InputInfo]() { return InputInfo.PointersArray; });
3050 TargetScope.addPrivate(SVD,
3051 [&InputInfo]() { return InputInfo.SizesArray; });
3052 }
3053 (void)TargetScope.Privatize();
3054 // Build list of dependences.
3055 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3056 for (auto *IRef : C->varlists())
3057 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3058 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3059 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3060 // Set proper addresses for generated private copies.
3061 OMPPrivateScope Scope(CGF);
3062 if (!Data.FirstprivateVars.empty()) {
3063 enum { PrivatesParam = 2, CopyFnParam = 3 };
3064 auto *CopyFn = CGF.Builder.CreateLoad(
3065 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3066 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3067 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3068 // Map privates.
3069 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3070 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3071 CallArgs.push_back(PrivatesPtr);
3072 for (auto *E : Data.FirstprivateVars) {
3073 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3074 Address PrivatePtr =
3075 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3076 ".firstpriv.ptr.addr");
3077 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3078 CallArgs.push_back(PrivatePtr.getPointer());
3079 }
3080 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3081 CopyFn, CallArgs);
3082 for (auto &&Pair : PrivatePtrs) {
3083 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3084 CGF.getContext().getDeclAlign(Pair.first));
3085 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3086 }
3087 }
3088 // Privatize all private variables except for in_reduction items.
3089 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003090 if (InputInfo.NumberOfTargetItems > 0) {
3091 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3092 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3093 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3094 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3095 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3096 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3097 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003098
3099 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003100 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003101 BodyGen(CGF);
3102 };
3103 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3104 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3105 Data.NumberOfParts);
3106 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3107 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3108 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3109 SourceLocation());
3110
3111 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3112 SharedsTy, CapturedStruct, &IfCond, Data);
3113}
3114
Alexey Bataev7292c292016-04-25 12:22:29 +00003115void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3116 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003117 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003118 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003119 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003120 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003121 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3122 if (C->getNameModifier() == OMPD_unknown ||
3123 C->getNameModifier() == OMPD_task) {
3124 IfCond = C->getCondition();
3125 break;
3126 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003127 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003128
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003129 OMPTaskDataTy Data;
3130 // Check if we should emit tied or untied task.
3131 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003132 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3133 CGF.EmitStmt(CS->getCapturedStmt());
3134 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003135 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003136 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003137 const OMPTaskDataTy &Data) {
3138 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3139 SharedsTy, CapturedStruct, IfCond,
3140 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003141 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003142 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003143}
3144
Alexey Bataev9f797f32015-02-05 05:57:51 +00003145void CodeGenFunction::EmitOMPTaskyieldDirective(
3146 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003147 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003148}
3149
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003150void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003151 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003152}
3153
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003154void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3155 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003156}
3157
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003158void CodeGenFunction::EmitOMPTaskgroupDirective(
3159 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3161 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003162 if (const Expr *E = S.getReductionRef()) {
3163 SmallVector<const Expr *, 4> LHSs;
3164 SmallVector<const Expr *, 4> RHSs;
3165 OMPTaskDataTy Data;
3166 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3167 auto IPriv = C->privates().begin();
3168 auto IRed = C->reduction_ops().begin();
3169 auto ILHS = C->lhs_exprs().begin();
3170 auto IRHS = C->rhs_exprs().begin();
3171 for (const auto *Ref : C->varlists()) {
3172 Data.ReductionVars.emplace_back(Ref);
3173 Data.ReductionCopies.emplace_back(*IPriv);
3174 Data.ReductionOps.emplace_back(*IRed);
3175 LHSs.emplace_back(*ILHS);
3176 RHSs.emplace_back(*IRHS);
3177 std::advance(IPriv, 1);
3178 std::advance(IRed, 1);
3179 std::advance(ILHS, 1);
3180 std::advance(IRHS, 1);
3181 }
3182 }
3183 llvm::Value *ReductionDesc =
3184 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3185 LHSs, RHSs, Data);
3186 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3187 CGF.EmitVarDecl(*VD);
3188 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3189 /*Volatile=*/false, E->getType());
3190 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003191 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003192 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003193 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003194 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3195}
3196
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003197void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003198 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003199 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003200 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3201 FlushClause->varlist_end());
3202 }
3203 return llvm::None;
3204 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003205}
3206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003207void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3208 const CodeGenLoopTy &CodeGenLoop,
3209 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003210 // Emit the loop iteration variable.
3211 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3212 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3213 EmitVarDecl(*IVDecl);
3214
3215 // Emit the iterations count variable.
3216 // If it is not a variable, Sema decided to calculate iterations count on each
3217 // iteration (e.g., it is foldable into a constant).
3218 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3219 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3220 // Emit calculation of the iterations count.
3221 EmitIgnoredExpr(S.getCalcLastIteration());
3222 }
3223
3224 auto &RT = CGM.getOpenMPRuntime();
3225
Carlo Bertolli962bb802017-01-03 18:24:42 +00003226 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003227 // Check pre-condition.
3228 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003229 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003230 // Skip the entire loop if we don't meet the precondition.
3231 // If the condition constant folds and can be elided, avoid emitting the
3232 // whole loop.
3233 bool CondConstant;
3234 llvm::BasicBlock *ContBlock = nullptr;
3235 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3236 if (!CondConstant)
3237 return;
3238 } else {
3239 auto *ThenBlock = createBasicBlock("omp.precond.then");
3240 ContBlock = createBasicBlock("omp.precond.end");
3241 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3242 getProfileCount(&S));
3243 EmitBlock(ThenBlock);
3244 incrementProfileCounter(&S);
3245 }
3246
Alexey Bataev617db5f2017-12-04 15:38:33 +00003247 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003248 // Emit 'then' code.
3249 {
3250 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003251
3252 LValue LB = EmitOMPHelperVar(
3253 *this, cast<DeclRefExpr>(
3254 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3255 ? S.getCombinedLowerBoundVariable()
3256 : S.getLowerBoundVariable())));
3257 LValue UB = EmitOMPHelperVar(
3258 *this, cast<DeclRefExpr>(
3259 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3260 ? S.getCombinedUpperBoundVariable()
3261 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003262 LValue ST =
3263 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3264 LValue IL =
3265 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3266
3267 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003268 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003269 // Emit implicit barrier to synchronize threads and avoid data races
3270 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003271 // lastprivate variables.
3272 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003273 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3274 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003275 }
3276 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003277 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003278 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3279 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003280 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003281 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003282 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003283 (void)LoopScope.Privatize();
3284
3285 // Detect the distribute schedule kind and chunk.
3286 llvm::Value *Chunk = nullptr;
3287 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3288 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3289 ScheduleKind = C->getDistScheduleKind();
3290 if (const auto *Ch = C->getChunkSize()) {
3291 Chunk = EmitScalarExpr(Ch);
3292 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003293 S.getIterationVariable()->getType(),
3294 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003295 }
3296 }
3297 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3298 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3299
3300 // OpenMP [2.10.8, distribute Construct, Description]
3301 // If dist_schedule is specified, kind must be static. If specified,
3302 // iterations are divided into chunks of size chunk_size, chunks are
3303 // assigned to the teams of the league in a round-robin fashion in the
3304 // order of the team number. When no chunk_size is specified, the
3305 // iteration space is divided into chunks that are approximately equal
3306 // in size, and at most one chunk is distributed to each team of the
3307 // league. The size of the chunks is unspecified in this case.
3308 if (RT.isStaticNonchunked(ScheduleKind,
3309 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003310 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3311 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003312 CGOpenMPRuntime::StaticRTInput StaticInit(
3313 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3314 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003315 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003316 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317 auto LoopExit =
3318 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3319 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003320 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3321 ? S.getCombinedEnsureUpperBound()
3322 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003323 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003324 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3325 ? S.getCombinedInit()
3326 : S.getInit());
3327
3328 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3329 ? S.getCombinedCond()
3330 : S.getCond();
3331
3332 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003333 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003334 // when combined with 'for' (e.g. as in 'distribute parallel for')
3335 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3336 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3337 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3338 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003339 },
3340 [](CodeGenFunction &) {});
3341 EmitBlock(LoopExit.getBlock());
3342 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003343 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003344 } else {
3345 // Emit the outer loop, which requests its work chunk [LB..UB] from
3346 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003347 const OMPLoopArguments LoopArguments = {
3348 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3349 Chunk};
3350 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3351 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003352 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003353 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3354 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3355 return CGF.Builder.CreateIsNotNull(
3356 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3357 });
3358 }
3359 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3360 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3361 isOpenMPSimdDirective(S.getDirectiveKind())) {
3362 ReductionKind = OMPD_parallel_for_simd;
3363 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3364 ReductionKind = OMPD_parallel_for;
3365 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3366 ReductionKind = OMPD_simd;
3367 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3368 S.hasClausesOfKind<OMPReductionClause>()) {
3369 llvm_unreachable(
3370 "No reduction clauses is allowed in distribute directive.");
3371 }
3372 EmitOMPReductionClauseFinal(S, ReductionKind);
3373 // Emit post-update of the reduction variables if IsLastIter != 0.
3374 emitPostUpdateForReductionClause(
3375 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3376 return CGF.Builder.CreateIsNotNull(
3377 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3378 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003379 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003380 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003381 EmitOMPLastprivateClauseFinal(
3382 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003383 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3384 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385 }
3386
3387 // We're now done with the loop, so jump to the continuation block.
3388 if (ContBlock) {
3389 EmitBranch(ContBlock);
3390 EmitBlock(ContBlock, true);
3391 }
3392 }
3393}
3394
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003395void CodeGenFunction::EmitOMPDistributeDirective(
3396 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003397 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003398
3399 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003400 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003401 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003402 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003403}
3404
Alexey Bataev5f600d62015-09-29 03:48:57 +00003405static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3406 const CapturedStmt *S) {
3407 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3408 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3409 CGF.CapturedStmtInfo = &CapStmtInfo;
3410 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3411 Fn->addFnAttr(llvm::Attribute::NoInline);
3412 return Fn;
3413}
3414
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003415void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003416 if (S.hasClausesOfKind<OMPDependClause>()) {
3417 assert(!S.getAssociatedStmt() &&
3418 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003419 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3420 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003421 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003422 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003423 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003424 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3425 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003426 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003427 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003428 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3429 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3430 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003431 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3432 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003433 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003434 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003435 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003436 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003437 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003438 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003439 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003440}
3441
Alexey Bataevb57056f2015-01-22 06:17:56 +00003442static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003443 QualType SrcType, QualType DestType,
3444 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003445 assert(CGF.hasScalarEvaluationKind(DestType) &&
3446 "DestType must have scalar evaluation kind.");
3447 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3448 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003449 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3450 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003451 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003452 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003453}
3454
3455static CodeGenFunction::ComplexPairTy
3456convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003457 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003458 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3459 "DestType must have complex evaluation kind.");
3460 CodeGenFunction::ComplexPairTy ComplexVal;
3461 if (Val.isScalar()) {
3462 // Convert the input element to the element type of the complex.
3463 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003464 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3465 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003466 ComplexVal = CodeGenFunction::ComplexPairTy(
3467 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3468 } else {
3469 assert(Val.isComplex() && "Must be a scalar or complex.");
3470 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3471 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3472 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003473 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003474 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003475 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003476 }
3477 return ComplexVal;
3478}
3479
Alexey Bataev5e018f92015-04-23 06:35:10 +00003480static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3481 LValue LVal, RValue RVal) {
3482 if (LVal.isGlobalReg()) {
3483 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3484 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003485 CGF.EmitAtomicStore(RVal, LVal,
3486 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3487 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003488 LVal.isVolatile(), /*IsInit=*/false);
3489 }
3490}
3491
Alexey Bataev8524d152016-01-21 12:35:58 +00003492void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3493 QualType RValTy, SourceLocation Loc) {
3494 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003495 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003496 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3497 *this, RVal, RValTy, LVal.getType(), Loc)),
3498 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003499 break;
3500 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003501 EmitStoreOfComplex(
3502 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003503 /*isInit=*/false);
3504 break;
3505 case TEK_Aggregate:
3506 llvm_unreachable("Must be a scalar or complex.");
3507 }
3508}
3509
Alexey Bataevb57056f2015-01-22 06:17:56 +00003510static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3511 const Expr *X, const Expr *V,
3512 SourceLocation Loc) {
3513 // v = x;
3514 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3515 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3516 LValue XLValue = CGF.EmitLValue(X);
3517 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003518 RValue Res = XLValue.isGlobalReg()
3519 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003520 : CGF.EmitAtomicLoad(
3521 XLValue, Loc,
3522 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3523 : llvm::AtomicOrdering::Monotonic,
3524 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003525 // OpenMP, 2.12.6, atomic Construct
3526 // Any atomic construct with a seq_cst clause forces the atomically
3527 // performed operation to include an implicit flush operation without a
3528 // list.
3529 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003530 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003531 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003532}
3533
Alexey Bataevb8329262015-02-27 06:33:30 +00003534static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3535 const Expr *X, const Expr *E,
3536 SourceLocation Loc) {
3537 // x = expr;
3538 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003539 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003540 // OpenMP, 2.12.6, atomic Construct
3541 // Any atomic construct with a seq_cst clause forces the atomically
3542 // performed operation to include an implicit flush operation without a
3543 // list.
3544 if (IsSeqCst)
3545 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3546}
3547
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003548static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3549 RValue Update,
3550 BinaryOperatorKind BO,
3551 llvm::AtomicOrdering AO,
3552 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003553 auto &Context = CGF.CGM.getContext();
3554 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003555 // expression is simple and atomic is allowed for the given type for the
3556 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003557 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003558 !Update.getScalarVal()->getType()->isIntegerTy() ||
3559 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3560 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003561 X.getAddress().getElementType())) ||
3562 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003563 !Context.getTargetInfo().hasBuiltinAtomic(
3564 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003565 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003566
3567 llvm::AtomicRMWInst::BinOp RMWOp;
3568 switch (BO) {
3569 case BO_Add:
3570 RMWOp = llvm::AtomicRMWInst::Add;
3571 break;
3572 case BO_Sub:
3573 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003574 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003575 RMWOp = llvm::AtomicRMWInst::Sub;
3576 break;
3577 case BO_And:
3578 RMWOp = llvm::AtomicRMWInst::And;
3579 break;
3580 case BO_Or:
3581 RMWOp = llvm::AtomicRMWInst::Or;
3582 break;
3583 case BO_Xor:
3584 RMWOp = llvm::AtomicRMWInst::Xor;
3585 break;
3586 case BO_LT:
3587 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3588 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3589 : llvm::AtomicRMWInst::Max)
3590 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3591 : llvm::AtomicRMWInst::UMax);
3592 break;
3593 case BO_GT:
3594 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3595 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3596 : llvm::AtomicRMWInst::Min)
3597 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3598 : llvm::AtomicRMWInst::UMin);
3599 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003600 case BO_Assign:
3601 RMWOp = llvm::AtomicRMWInst::Xchg;
3602 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003603 case BO_Mul:
3604 case BO_Div:
3605 case BO_Rem:
3606 case BO_Shl:
3607 case BO_Shr:
3608 case BO_LAnd:
3609 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003610 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003611 case BO_PtrMemD:
3612 case BO_PtrMemI:
3613 case BO_LE:
3614 case BO_GE:
3615 case BO_EQ:
3616 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003617 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003618 case BO_AddAssign:
3619 case BO_SubAssign:
3620 case BO_AndAssign:
3621 case BO_OrAssign:
3622 case BO_XorAssign:
3623 case BO_MulAssign:
3624 case BO_DivAssign:
3625 case BO_RemAssign:
3626 case BO_ShlAssign:
3627 case BO_ShrAssign:
3628 case BO_Comma:
3629 llvm_unreachable("Unsupported atomic update operation");
3630 }
3631 auto *UpdateVal = Update.getScalarVal();
3632 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3633 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003634 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003635 X.getType()->hasSignedIntegerRepresentation());
3636 }
John McCall7f416cc2015-09-08 08:05:57 +00003637 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003638 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003639}
3640
Alexey Bataev5e018f92015-04-23 06:35:10 +00003641std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003642 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3643 llvm::AtomicOrdering AO, SourceLocation Loc,
3644 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3645 // Update expressions are allowed to have the following forms:
3646 // x binop= expr; -> xrval + expr;
3647 // x++, ++x -> xrval + 1;
3648 // x--, --x -> xrval - 1;
3649 // x = x binop expr; -> xrval binop expr
3650 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003651 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3652 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003653 if (X.isGlobalReg()) {
3654 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3655 // 'xrval'.
3656 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3657 } else {
3658 // Perform compare-and-swap procedure.
3659 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003660 }
3661 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003662 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003663}
3664
3665static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3666 const Expr *X, const Expr *E,
3667 const Expr *UE, bool IsXLHSInRHSPart,
3668 SourceLocation Loc) {
3669 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3670 "Update expr in 'atomic update' must be a binary operator.");
3671 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3672 // Update expressions are allowed to have the following forms:
3673 // x binop= expr; -> xrval + expr;
3674 // x++, ++x -> xrval + 1;
3675 // x--, --x -> xrval - 1;
3676 // x = x binop expr; -> xrval binop expr
3677 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003678 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003679 LValue XLValue = CGF.EmitLValue(X);
3680 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003681 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3682 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003683 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3684 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3685 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3686 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3687 auto Gen =
3688 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3689 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3690 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3691 return CGF.EmitAnyExpr(UE);
3692 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003693 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3694 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3695 // OpenMP, 2.12.6, atomic Construct
3696 // Any atomic construct with a seq_cst clause forces the atomically
3697 // performed operation to include an implicit flush operation without a
3698 // list.
3699 if (IsSeqCst)
3700 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3701}
3702
3703static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003704 QualType SourceType, QualType ResType,
3705 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003706 switch (CGF.getEvaluationKind(ResType)) {
3707 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003708 return RValue::get(
3709 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003710 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003711 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003712 return RValue::getComplex(Res.first, Res.second);
3713 }
3714 case TEK_Aggregate:
3715 break;
3716 }
3717 llvm_unreachable("Must be a scalar or complex.");
3718}
3719
3720static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3721 bool IsPostfixUpdate, const Expr *V,
3722 const Expr *X, const Expr *E,
3723 const Expr *UE, bool IsXLHSInRHSPart,
3724 SourceLocation Loc) {
3725 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3726 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3727 RValue NewVVal;
3728 LValue VLValue = CGF.EmitLValue(V);
3729 LValue XLValue = CGF.EmitLValue(X);
3730 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003731 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3732 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003733 QualType NewVValType;
3734 if (UE) {
3735 // 'x' is updated with some additional value.
3736 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3737 "Update expr in 'atomic capture' must be a binary operator.");
3738 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3739 // Update expressions are allowed to have the following forms:
3740 // x binop= expr; -> xrval + expr;
3741 // x++, ++x -> xrval + 1;
3742 // x--, --x -> xrval - 1;
3743 // x = x binop expr; -> xrval binop expr
3744 // x = expr Op x; - > expr binop xrval;
3745 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3746 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3747 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3748 NewVValType = XRValExpr->getType();
3749 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3750 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003751 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003752 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3753 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3754 RValue Res = CGF.EmitAnyExpr(UE);
3755 NewVVal = IsPostfixUpdate ? XRValue : Res;
3756 return Res;
3757 };
3758 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3759 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3760 if (Res.first) {
3761 // 'atomicrmw' instruction was generated.
3762 if (IsPostfixUpdate) {
3763 // Use old value from 'atomicrmw'.
3764 NewVVal = Res.second;
3765 } else {
3766 // 'atomicrmw' does not provide new value, so evaluate it using old
3767 // value of 'x'.
3768 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3769 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3770 NewVVal = CGF.EmitAnyExpr(UE);
3771 }
3772 }
3773 } else {
3774 // 'x' is simply rewritten with some 'expr'.
3775 NewVValType = X->getType().getNonReferenceType();
3776 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003777 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003778 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003779 NewVVal = XRValue;
3780 return ExprRValue;
3781 };
3782 // Try to perform atomicrmw xchg, otherwise simple exchange.
3783 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3784 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3785 Loc, Gen);
3786 if (Res.first) {
3787 // 'atomicrmw' instruction was generated.
3788 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3789 }
3790 }
3791 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003792 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003793 // OpenMP, 2.12.6, atomic Construct
3794 // Any atomic construct with a seq_cst clause forces the atomically
3795 // performed operation to include an implicit flush operation without a
3796 // list.
3797 if (IsSeqCst)
3798 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3799}
3800
Alexey Bataevb57056f2015-01-22 06:17:56 +00003801static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003802 bool IsSeqCst, bool IsPostfixUpdate,
3803 const Expr *X, const Expr *V, const Expr *E,
3804 const Expr *UE, bool IsXLHSInRHSPart,
3805 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003806 switch (Kind) {
3807 case OMPC_read:
3808 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3809 break;
3810 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003811 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3812 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003813 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003814 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003815 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3816 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003817 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003818 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3819 IsXLHSInRHSPart, Loc);
3820 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003821 case OMPC_if:
3822 case OMPC_final:
3823 case OMPC_num_threads:
3824 case OMPC_private:
3825 case OMPC_firstprivate:
3826 case OMPC_lastprivate:
3827 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003828 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003829 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003830 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003831 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003832 case OMPC_collapse:
3833 case OMPC_default:
3834 case OMPC_seq_cst:
3835 case OMPC_shared:
3836 case OMPC_linear:
3837 case OMPC_aligned:
3838 case OMPC_copyin:
3839 case OMPC_copyprivate:
3840 case OMPC_flush:
3841 case OMPC_proc_bind:
3842 case OMPC_schedule:
3843 case OMPC_ordered:
3844 case OMPC_nowait:
3845 case OMPC_untied:
3846 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003847 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003848 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003849 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003850 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003851 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003852 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003853 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003854 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003855 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003856 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003857 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003858 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003859 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003860 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003861 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003862 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003863 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003864 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003865 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003866 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003867 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3868 }
3869}
3870
3871void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003872 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003873 OpenMPClauseKind Kind = OMPC_unknown;
3874 for (auto *C : S.clauses()) {
3875 // Find first clause (skip seq_cst clause, if it is first).
3876 if (C->getClauseKind() != OMPC_seq_cst) {
3877 Kind = C->getClauseKind();
3878 break;
3879 }
3880 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003881
Alexey Bataev475a7442018-01-12 19:39:11 +00003882 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003883 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003884 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003885 }
3886 // Processing for statements under 'atomic capture'.
3887 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3888 for (const auto *C : Compound->body()) {
3889 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3890 enterFullExpression(EWC);
3891 }
3892 }
3893 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003894
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003895 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3896 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003897 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003898 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3899 S.getV(), S.getExpr(), S.getUpdateExpr(),
3900 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003901 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003902 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003903 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003904}
3905
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003906static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3907 const OMPExecutableDirective &S,
3908 const RegionCodeGenTy &CodeGen) {
3909 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3910 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003911
Samuel Antaoee8fb302016-01-06 13:42:12 +00003912 llvm::Function *Fn = nullptr;
3913 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003914
Samuel Antaobed3c462015-10-02 16:14:20 +00003915 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003916 // Check for the at most one if clause associated with the target region.
3917 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3918 if (C->getNameModifier() == OMPD_unknown ||
3919 C->getNameModifier() == OMPD_target) {
3920 IfCond = C->getCondition();
3921 break;
3922 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003923 }
3924
3925 // Check if we have any device clause associated with the directive.
3926 const Expr *Device = nullptr;
3927 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3928 Device = C->getDevice();
3929 }
3930
Samuel Antaoee8fb302016-01-06 13:42:12 +00003931 // Check if we have an if clause whose conditional always evaluates to false
3932 // or if we do not have any targets specified. If so the target region is not
3933 // an offload entry point.
3934 bool IsOffloadEntry = true;
3935 if (IfCond) {
3936 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003937 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003938 IsOffloadEntry = false;
3939 }
3940 if (CGM.getLangOpts().OMPTargetTriples.empty())
3941 IsOffloadEntry = false;
3942
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003943 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944 StringRef ParentName;
3945 // In case we have Ctors/Dtors we use the complete type variant to produce
3946 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003947 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003949 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003950 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3951 else
3952 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003953 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003954
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003955 // Emit target region as a standalone region.
3956 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3957 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003958 OMPLexicalScope Scope(CGF, S, OMPD_task);
3959 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003960}
3961
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003962static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3963 PrePostActionTy &Action) {
3964 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3965 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3966 CGF.EmitOMPPrivateClause(S, PrivateScope);
3967 (void)PrivateScope.Privatize();
3968
3969 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003970 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003971}
3972
3973void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3974 StringRef ParentName,
3975 const OMPTargetDirective &S) {
3976 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3977 emitTargetRegion(CGF, S, Action);
3978 };
3979 llvm::Function *Fn;
3980 llvm::Constant *Addr;
3981 // Emit target region as a standalone region.
3982 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3983 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3984 assert(Fn && Addr && "Target device function emission failed.");
3985}
3986
3987void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3988 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3989 emitTargetRegion(CGF, S, Action);
3990 };
3991 emitCommonOMPTargetDirective(*this, S, CodeGen);
3992}
3993
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003994static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3995 const OMPExecutableDirective &S,
3996 OpenMPDirectiveKind InnermostKind,
3997 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003998 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3999 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4000 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004001
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004002 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4003 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004004 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004005 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4006 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004007
Carlo Bertollic6872252016-04-04 15:55:02 +00004008 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4009 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004010 }
4011
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004012 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004013 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4014 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004015 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4016 CapturedVars);
4017}
4018
4019void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004020 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004021 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004022 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004023 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4024 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004025 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004026 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004027 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004028 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004029 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004030 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004031 emitPostUpdateForReductionClause(
4032 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004033}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004034
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004035static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4036 const OMPTargetTeamsDirective &S) {
4037 auto *CS = S.getCapturedStmt(OMPD_teams);
4038 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004039 // Emit teams region as a standalone region.
4040 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4041 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4042 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4043 CGF.EmitOMPPrivateClause(S, PrivateScope);
4044 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4045 (void)PrivateScope.Privatize();
4046 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004047 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004048 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004049 };
4050 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004051 emitPostUpdateForReductionClause(
4052 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004053}
4054
4055void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4056 CodeGenModule &CGM, StringRef ParentName,
4057 const OMPTargetTeamsDirective &S) {
4058 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4059 emitTargetTeamsRegion(CGF, Action, S);
4060 };
4061 llvm::Function *Fn;
4062 llvm::Constant *Addr;
4063 // Emit target region as a standalone region.
4064 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4065 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4066 assert(Fn && Addr && "Target device function emission failed.");
4067}
4068
4069void CodeGenFunction::EmitOMPTargetTeamsDirective(
4070 const OMPTargetTeamsDirective &S) {
4071 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4072 emitTargetTeamsRegion(CGF, Action, S);
4073 };
4074 emitCommonOMPTargetDirective(*this, S, CodeGen);
4075}
4076
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004077static void
4078emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4079 const OMPTargetTeamsDistributeDirective &S) {
4080 Action.Enter(CGF);
4081 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4082 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4083 };
4084
4085 // Emit teams region as a standalone region.
4086 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4087 PrePostActionTy &) {
4088 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4089 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4090 (void)PrivateScope.Privatize();
4091 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4092 CodeGenDistribute);
4093 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4094 };
4095 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4096 emitPostUpdateForReductionClause(CGF, S,
4097 [](CodeGenFunction &) { return nullptr; });
4098}
4099
4100void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4101 CodeGenModule &CGM, StringRef ParentName,
4102 const OMPTargetTeamsDistributeDirective &S) {
4103 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4104 emitTargetTeamsDistributeRegion(CGF, Action, S);
4105 };
4106 llvm::Function *Fn;
4107 llvm::Constant *Addr;
4108 // Emit target region as a standalone region.
4109 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4110 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4111 assert(Fn && Addr && "Target device function emission failed.");
4112}
4113
4114void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4115 const OMPTargetTeamsDistributeDirective &S) {
4116 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4117 emitTargetTeamsDistributeRegion(CGF, Action, S);
4118 };
4119 emitCommonOMPTargetDirective(*this, S, CodeGen);
4120}
4121
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004122static void emitTargetTeamsDistributeSimdRegion(
4123 CodeGenFunction &CGF, PrePostActionTy &Action,
4124 const OMPTargetTeamsDistributeSimdDirective &S) {
4125 Action.Enter(CGF);
4126 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4127 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4128 };
4129
4130 // Emit teams region as a standalone region.
4131 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4132 PrePostActionTy &) {
4133 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4134 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4135 (void)PrivateScope.Privatize();
4136 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4137 CodeGenDistribute);
4138 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4139 };
4140 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4141 emitPostUpdateForReductionClause(CGF, S,
4142 [](CodeGenFunction &) { return nullptr; });
4143}
4144
4145void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4146 CodeGenModule &CGM, StringRef ParentName,
4147 const OMPTargetTeamsDistributeSimdDirective &S) {
4148 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4149 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4150 };
4151 llvm::Function *Fn;
4152 llvm::Constant *Addr;
4153 // Emit target region as a standalone region.
4154 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4155 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4156 assert(Fn && Addr && "Target device function emission failed.");
4157}
4158
4159void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4160 const OMPTargetTeamsDistributeSimdDirective &S) {
4161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4162 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4163 };
4164 emitCommonOMPTargetDirective(*this, S, CodeGen);
4165}
4166
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004167void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4168 const OMPTeamsDistributeDirective &S) {
4169
4170 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4171 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4172 };
4173
4174 // Emit teams region as a standalone region.
4175 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4176 PrePostActionTy &) {
4177 OMPPrivateScope PrivateScope(CGF);
4178 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4179 (void)PrivateScope.Privatize();
4180 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4181 CodeGenDistribute);
4182 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4183 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004184 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004185 emitPostUpdateForReductionClause(*this, S,
4186 [](CodeGenFunction &) { return nullptr; });
4187}
4188
Alexey Bataev999277a2017-12-06 14:31:09 +00004189void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4190 const OMPTeamsDistributeSimdDirective &S) {
4191 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4192 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4193 };
4194
4195 // Emit teams region as a standalone region.
4196 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4197 PrePostActionTy &) {
4198 OMPPrivateScope PrivateScope(CGF);
4199 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4200 (void)PrivateScope.Privatize();
4201 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4202 CodeGenDistribute);
4203 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4204 };
4205 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4206 emitPostUpdateForReductionClause(*this, S,
4207 [](CodeGenFunction &) { return nullptr; });
4208}
4209
Carlo Bertolli62fae152017-11-20 20:46:39 +00004210void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4211 const OMPTeamsDistributeParallelForDirective &S) {
4212 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4213 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4214 S.getDistInc());
4215 };
4216
4217 // Emit teams region as a standalone region.
4218 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4219 PrePostActionTy &) {
4220 OMPPrivateScope PrivateScope(CGF);
4221 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4222 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004223 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4224 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004225 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4226 };
4227 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4228 emitPostUpdateForReductionClause(*this, S,
4229 [](CodeGenFunction &) { return nullptr; });
4230}
4231
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004232void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4233 const OMPTeamsDistributeParallelForSimdDirective &S) {
4234 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4235 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4236 S.getDistInc());
4237 };
4238
4239 // Emit teams region as a standalone region.
4240 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4241 PrePostActionTy &) {
4242 OMPPrivateScope PrivateScope(CGF);
4243 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4244 (void)PrivateScope.Privatize();
4245 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4246 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4247 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4248 };
4249 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4250 emitPostUpdateForReductionClause(*this, S,
4251 [](CodeGenFunction &) { return nullptr; });
4252}
4253
Carlo Bertolli52978c32018-01-03 21:12:44 +00004254static void emitTargetTeamsDistributeParallelForRegion(
4255 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4256 PrePostActionTy &Action) {
4257 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4258 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4259 S.getDistInc());
4260 };
4261
4262 // Emit teams region as a standalone region.
4263 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4264 PrePostActionTy &) {
4265 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4266 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4267 (void)PrivateScope.Privatize();
4268 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4269 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4270 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4271 };
4272
4273 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4274 CodeGenTeams);
4275 emitPostUpdateForReductionClause(CGF, S,
4276 [](CodeGenFunction &) { return nullptr; });
4277}
4278
4279void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4280 CodeGenModule &CGM, StringRef ParentName,
4281 const OMPTargetTeamsDistributeParallelForDirective &S) {
4282 // Emit SPMD target teams distribute parallel for region as a standalone
4283 // region.
4284 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4285 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4286 };
4287 llvm::Function *Fn;
4288 llvm::Constant *Addr;
4289 // Emit target region as a standalone region.
4290 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4291 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4292 assert(Fn && Addr && "Target device function emission failed.");
4293}
4294
4295void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4296 const OMPTargetTeamsDistributeParallelForDirective &S) {
4297 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4298 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4299 };
4300 emitCommonOMPTargetDirective(*this, S, CodeGen);
4301}
4302
Alexey Bataev647dd842018-01-15 20:59:40 +00004303static void emitTargetTeamsDistributeParallelForSimdRegion(
4304 CodeGenFunction &CGF,
4305 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4306 PrePostActionTy &Action) {
4307 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4308 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4309 S.getDistInc());
4310 };
4311
4312 // Emit teams region as a standalone region.
4313 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4314 PrePostActionTy &) {
4315 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4316 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4317 (void)PrivateScope.Privatize();
4318 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4319 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4320 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4321 };
4322
4323 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4324 CodeGenTeams);
4325 emitPostUpdateForReductionClause(CGF, S,
4326 [](CodeGenFunction &) { return nullptr; });
4327}
4328
4329void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4330 CodeGenModule &CGM, StringRef ParentName,
4331 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4332 // Emit SPMD target teams distribute parallel for simd region as a standalone
4333 // region.
4334 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4335 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4336 };
4337 llvm::Function *Fn;
4338 llvm::Constant *Addr;
4339 // Emit target region as a standalone region.
4340 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4341 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4342 assert(Fn && Addr && "Target device function emission failed.");
4343}
4344
4345void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4346 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4347 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4348 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4349 };
4350 emitCommonOMPTargetDirective(*this, S, CodeGen);
4351}
4352
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004353void CodeGenFunction::EmitOMPCancellationPointDirective(
4354 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004355 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4356 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004357}
4358
Alexey Bataev80909872015-07-02 11:25:17 +00004359void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004360 const Expr *IfCond = nullptr;
4361 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4362 if (C->getNameModifier() == OMPD_unknown ||
4363 C->getNameModifier() == OMPD_cancel) {
4364 IfCond = C->getCondition();
4365 break;
4366 }
4367 }
4368 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004369 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004370}
4371
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004372CodeGenFunction::JumpDest
4373CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004374 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4375 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004376 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004377 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004378 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4379 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004380 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004381 Kind == OMPD_teams_distribute_parallel_for ||
4382 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004383 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004384}
Michael Wong65f367f2015-07-21 13:44:28 +00004385
Samuel Antaocc10b852016-07-28 14:23:26 +00004386void CodeGenFunction::EmitOMPUseDevicePtrClause(
4387 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4388 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4389 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4390 auto OrigVarIt = C.varlist_begin();
4391 auto InitIt = C.inits().begin();
4392 for (auto PvtVarIt : C.private_copies()) {
4393 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4394 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4395 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4396
4397 // In order to identify the right initializer we need to match the
4398 // declaration used by the mapping logic. In some cases we may get
4399 // OMPCapturedExprDecl that refers to the original declaration.
4400 const ValueDecl *MatchingVD = OrigVD;
4401 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4402 // OMPCapturedExprDecl are used to privative fields of the current
4403 // structure.
4404 auto *ME = cast<MemberExpr>(OED->getInit());
4405 assert(isa<CXXThisExpr>(ME->getBase()) &&
4406 "Base should be the current struct!");
4407 MatchingVD = ME->getMemberDecl();
4408 }
4409
4410 // If we don't have information about the current list item, move on to
4411 // the next one.
4412 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4413 if (InitAddrIt == CaptureDeviceAddrMap.end())
4414 continue;
4415
4416 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4417 // Initialize the temporary initialization variable with the address we
4418 // get from the runtime library. We have to cast the source address
4419 // because it is always a void *. References are materialized in the
4420 // privatization scope, so the initialization here disregards the fact
4421 // the original variable is a reference.
4422 QualType AddrQTy =
4423 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4424 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4425 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4426 setAddrOfLocalVar(InitVD, InitAddr);
4427
4428 // Emit private declaration, it will be initialized by the value we
4429 // declaration we just added to the local declarations map.
4430 EmitDecl(*PvtVD);
4431
4432 // The initialization variables reached its purpose in the emission
4433 // ofthe previous declaration, so we don't need it anymore.
4434 LocalDeclMap.erase(InitVD);
4435
4436 // Return the address of the private variable.
4437 return GetAddrOfLocalVar(PvtVD);
4438 });
4439 assert(IsRegistered && "firstprivate var already registered as private");
4440 // Silence the warning about unused variable.
4441 (void)IsRegistered;
4442
4443 ++OrigVarIt;
4444 ++InitIt;
4445 }
4446}
4447
Michael Wong65f367f2015-07-21 13:44:28 +00004448// Generate the instructions for '#pragma omp target data' directive.
4449void CodeGenFunction::EmitOMPTargetDataDirective(
4450 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004451 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4452
4453 // Create a pre/post action to signal the privatization of the device pointer.
4454 // This action can be replaced by the OpenMP runtime code generation to
4455 // deactivate privatization.
4456 bool PrivatizeDevicePointers = false;
4457 class DevicePointerPrivActionTy : public PrePostActionTy {
4458 bool &PrivatizeDevicePointers;
4459
4460 public:
4461 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4462 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4463 void Enter(CodeGenFunction &CGF) override {
4464 PrivatizeDevicePointers = true;
4465 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004466 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004467 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4468
4469 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004470 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004471 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004472 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004473 };
4474
4475 // Codegen that selects wheather to generate the privatization code or not.
4476 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4477 &InnermostCodeGen](CodeGenFunction &CGF,
4478 PrePostActionTy &Action) {
4479 RegionCodeGenTy RCG(InnermostCodeGen);
4480 PrivatizeDevicePointers = false;
4481
4482 // Call the pre-action to change the status of PrivatizeDevicePointers if
4483 // needed.
4484 Action.Enter(CGF);
4485
4486 if (PrivatizeDevicePointers) {
4487 OMPPrivateScope PrivateScope(CGF);
4488 // Emit all instances of the use_device_ptr clause.
4489 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4490 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4491 Info.CaptureDeviceAddrMap);
4492 (void)PrivateScope.Privatize();
4493 RCG(CGF);
4494 } else
4495 RCG(CGF);
4496 };
4497
4498 // Forward the provided action to the privatization codegen.
4499 RegionCodeGenTy PrivRCG(PrivCodeGen);
4500 PrivRCG.setAction(Action);
4501
4502 // Notwithstanding the body of the region is emitted as inlined directive,
4503 // we don't use an inline scope as changes in the references inside the
4504 // region are expected to be visible outside, so we do not privative them.
4505 OMPLexicalScope Scope(CGF, S);
4506 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4507 PrivRCG);
4508 };
4509
4510 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004511
4512 // If we don't have target devices, don't bother emitting the data mapping
4513 // code.
4514 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004515 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004516 return;
4517 }
4518
4519 // Check if we have any if clause associated with the directive.
4520 const Expr *IfCond = nullptr;
4521 if (auto *C = S.getSingleClause<OMPIfClause>())
4522 IfCond = C->getCondition();
4523
4524 // Check if we have any device clause associated with the directive.
4525 const Expr *Device = nullptr;
4526 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4527 Device = C->getDevice();
4528
Samuel Antaocc10b852016-07-28 14:23:26 +00004529 // Set the action to signal privatization of device pointers.
4530 RCG.setAction(PrivAction);
4531
4532 // Emit region code.
4533 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4534 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004535}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004536
Samuel Antaodf67fc42016-01-19 19:15:56 +00004537void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4538 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004539 // If we don't have target devices, don't bother emitting the data mapping
4540 // code.
4541 if (CGM.getLangOpts().OMPTargetTriples.empty())
4542 return;
4543
4544 // Check if we have any if clause associated with the directive.
4545 const Expr *IfCond = nullptr;
4546 if (auto *C = S.getSingleClause<OMPIfClause>())
4547 IfCond = C->getCondition();
4548
4549 // Check if we have any device clause associated with the directive.
4550 const Expr *Device = nullptr;
4551 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4552 Device = C->getDevice();
4553
Alexey Bataev475a7442018-01-12 19:39:11 +00004554 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004555 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004556}
4557
Samuel Antao72590762016-01-19 20:04:50 +00004558void CodeGenFunction::EmitOMPTargetExitDataDirective(
4559 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004560 // If we don't have target devices, don't bother emitting the data mapping
4561 // code.
4562 if (CGM.getLangOpts().OMPTargetTriples.empty())
4563 return;
4564
4565 // Check if we have any if clause associated with the directive.
4566 const Expr *IfCond = nullptr;
4567 if (auto *C = S.getSingleClause<OMPIfClause>())
4568 IfCond = C->getCondition();
4569
4570 // Check if we have any device clause associated with the directive.
4571 const Expr *Device = nullptr;
4572 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4573 Device = C->getDevice();
4574
Alexey Bataev475a7442018-01-12 19:39:11 +00004575 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004576 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004577}
4578
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004579static void emitTargetParallelRegion(CodeGenFunction &CGF,
4580 const OMPTargetParallelDirective &S,
4581 PrePostActionTy &Action) {
4582 // Get the captured statement associated with the 'parallel' region.
4583 auto *CS = S.getCapturedStmt(OMPD_parallel);
4584 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004585 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4586 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4587 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4588 CGF.EmitOMPPrivateClause(S, PrivateScope);
4589 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4590 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004591 // TODO: Add support for clauses.
4592 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004593 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004594 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004595 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4596 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004597 emitPostUpdateForReductionClause(
4598 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004599}
4600
4601void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4602 CodeGenModule &CGM, StringRef ParentName,
4603 const OMPTargetParallelDirective &S) {
4604 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4605 emitTargetParallelRegion(CGF, S, Action);
4606 };
4607 llvm::Function *Fn;
4608 llvm::Constant *Addr;
4609 // Emit target region as a standalone region.
4610 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4611 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4612 assert(Fn && Addr && "Target device function emission failed.");
4613}
4614
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004615void CodeGenFunction::EmitOMPTargetParallelDirective(
4616 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004617 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4618 emitTargetParallelRegion(CGF, S, Action);
4619 };
4620 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004621}
4622
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004623static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4624 const OMPTargetParallelForDirective &S,
4625 PrePostActionTy &Action) {
4626 Action.Enter(CGF);
4627 // Emit directive as a combined directive that consists of two implicit
4628 // directives: 'parallel' with 'for' directive.
4629 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004630 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4631 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004632 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4633 emitDispatchForLoopBounds);
4634 };
4635 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4636 emitEmptyBoundParameters);
4637}
4638
4639void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4640 CodeGenModule &CGM, StringRef ParentName,
4641 const OMPTargetParallelForDirective &S) {
4642 // Emit SPMD target parallel for region as a standalone region.
4643 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4644 emitTargetParallelForRegion(CGF, S, Action);
4645 };
4646 llvm::Function *Fn;
4647 llvm::Constant *Addr;
4648 // Emit target region as a standalone region.
4649 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4650 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4651 assert(Fn && Addr && "Target device function emission failed.");
4652}
4653
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004654void CodeGenFunction::EmitOMPTargetParallelForDirective(
4655 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004656 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4657 emitTargetParallelForRegion(CGF, S, Action);
4658 };
4659 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004660}
4661
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004662static void
4663emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4664 const OMPTargetParallelForSimdDirective &S,
4665 PrePostActionTy &Action) {
4666 Action.Enter(CGF);
4667 // Emit directive as a combined directive that consists of two implicit
4668 // directives: 'parallel' with 'for' directive.
4669 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4670 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4671 emitDispatchForLoopBounds);
4672 };
4673 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4674 emitEmptyBoundParameters);
4675}
4676
4677void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4678 CodeGenModule &CGM, StringRef ParentName,
4679 const OMPTargetParallelForSimdDirective &S) {
4680 // Emit SPMD target parallel for region as a standalone region.
4681 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4682 emitTargetParallelForSimdRegion(CGF, S, Action);
4683 };
4684 llvm::Function *Fn;
4685 llvm::Constant *Addr;
4686 // Emit target region as a standalone region.
4687 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4688 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4689 assert(Fn && Addr && "Target device function emission failed.");
4690}
4691
4692void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4693 const OMPTargetParallelForSimdDirective &S) {
4694 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4695 emitTargetParallelForSimdRegion(CGF, S, Action);
4696 };
4697 emitCommonOMPTargetDirective(*this, S, CodeGen);
4698}
4699
Alexey Bataev7292c292016-04-25 12:22:29 +00004700/// Emit a helper variable and return corresponding lvalue.
4701static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4702 const ImplicitParamDecl *PVD,
4703 CodeGenFunction::OMPPrivateScope &Privates) {
4704 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4705 Privates.addPrivate(
4706 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4707}
4708
4709void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4710 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4711 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004712 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004713 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4714 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4715 const Expr *IfCond = nullptr;
4716 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4717 if (C->getNameModifier() == OMPD_unknown ||
4718 C->getNameModifier() == OMPD_taskloop) {
4719 IfCond = C->getCondition();
4720 break;
4721 }
4722 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004723
4724 OMPTaskDataTy Data;
4725 // Check if taskloop must be emitted without taskgroup.
4726 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004727 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004728 Data.Tied = true;
4729 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004730 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4731 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004732 Data.Schedule.setInt(/*IntVal=*/false);
4733 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004734 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4735 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004736 Data.Schedule.setInt(/*IntVal=*/true);
4737 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004738 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004739
4740 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4741 // if (PreCond) {
4742 // for (IV in 0..LastIteration) BODY;
4743 // <Final counter/linear vars updates>;
4744 // }
4745 //
4746
4747 // Emit: if (PreCond) - begin.
4748 // If the condition constant folds and can be elided, avoid emitting the
4749 // whole loop.
4750 bool CondConstant;
4751 llvm::BasicBlock *ContBlock = nullptr;
4752 OMPLoopScope PreInitScope(CGF, S);
4753 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4754 if (!CondConstant)
4755 return;
4756 } else {
4757 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4758 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4759 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4760 CGF.getProfileCount(&S));
4761 CGF.EmitBlock(ThenBlock);
4762 CGF.incrementProfileCounter(&S);
4763 }
4764
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004765 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4766 CGF.EmitOMPSimdInit(S);
4767
Alexey Bataev7292c292016-04-25 12:22:29 +00004768 OMPPrivateScope LoopScope(CGF);
4769 // Emit helper vars inits.
4770 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4771 auto *I = CS->getCapturedDecl()->param_begin();
4772 auto *LBP = std::next(I, LowerBound);
4773 auto *UBP = std::next(I, UpperBound);
4774 auto *STP = std::next(I, Stride);
4775 auto *LIP = std::next(I, LastIter);
4776 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4777 LoopScope);
4778 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4779 LoopScope);
4780 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4781 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4782 LoopScope);
4783 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004784 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004785 (void)LoopScope.Privatize();
4786 // Emit the loop iteration variable.
4787 const Expr *IVExpr = S.getIterationVariable();
4788 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4789 CGF.EmitVarDecl(*IVDecl);
4790 CGF.EmitIgnoredExpr(S.getInit());
4791
4792 // Emit the iterations count variable.
4793 // If it is not a variable, Sema decided to calculate iterations count on
4794 // each iteration (e.g., it is foldable into a constant).
4795 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4796 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4797 // Emit calculation of the iterations count.
4798 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4799 }
4800
4801 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4802 S.getInc(),
4803 [&S](CodeGenFunction &CGF) {
4804 CGF.EmitOMPLoopBody(S, JumpDest());
4805 CGF.EmitStopPoint(&S);
4806 },
4807 [](CodeGenFunction &) {});
4808 // Emit: if (PreCond) - end.
4809 if (ContBlock) {
4810 CGF.EmitBranch(ContBlock);
4811 CGF.EmitBlock(ContBlock, true);
4812 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004813 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4814 if (HasLastprivateClause) {
4815 CGF.EmitOMPLastprivateClauseFinal(
4816 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4817 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4818 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4819 (*LIP)->getType(), S.getLocStart())));
4820 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004821 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004822 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4823 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4824 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004825 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4826 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004827 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4828 OutlinedFn, SharedsTy,
4829 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004830 };
4831 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4832 CodeGen);
4833 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004834 if (Data.Nogroup) {
4835 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4836 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004837 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4838 *this,
4839 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4840 PrePostActionTy &Action) {
4841 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004842 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4843 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004844 },
4845 S.getLocStart());
4846 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004847}
4848
Alexey Bataev49f6e782015-12-01 04:18:41 +00004849void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004850 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004851}
4852
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004853void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4854 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004855 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004856}
Samuel Antao686c70c2016-05-26 17:30:50 +00004857
4858// Generate the instructions for '#pragma omp target update' directive.
4859void CodeGenFunction::EmitOMPTargetUpdateDirective(
4860 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004861 // If we don't have target devices, don't bother emitting the data mapping
4862 // code.
4863 if (CGM.getLangOpts().OMPTargetTriples.empty())
4864 return;
4865
4866 // Check if we have any if clause associated with the directive.
4867 const Expr *IfCond = nullptr;
4868 if (auto *C = S.getSingleClause<OMPIfClause>())
4869 IfCond = C->getCondition();
4870
4871 // Check if we have any device clause associated with the directive.
4872 const Expr *Device = nullptr;
4873 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4874 Device = C->getDevice();
4875
Alexey Bataev475a7442018-01-12 19:39:11 +00004876 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004877 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004878}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004879
4880void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4881 const OMPExecutableDirective &D) {
4882 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4883 return;
4884 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4885 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4886 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4887 } else {
4888 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4889 for (const auto *E : LD->counters()) {
4890 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4891 cast<DeclRefExpr>(E)->getDecl())) {
4892 // Emit only those that were not explicitly referenced in clauses.
4893 if (!CGF.LocalDeclMap.count(VD))
4894 CGF.EmitVarDecl(*VD);
4895 }
4896 }
4897 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004898 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004899 }
4900 };
4901 OMPSimdLexicalScope Scope(*this, D);
4902 CGM.getOpenMPRuntime().emitInlinedDirective(
4903 *this,
4904 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4905 : D.getDirectiveKind(),
4906 CodeGen);
4907}