blob: 9d077a2be16cc398ae00020f811a9f1116c119af [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 Bataevab4ea222018-03-07 18:17:06 +0000123 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000126 (void)PreCondVars.setVarAddr(
127 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000128 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000129 (void)PreCondVars.apply(CGF);
George Burgess IV00f70bd2018-03-01 05:43:23 +0000130 if (auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
131 for (const auto *I : PreInits->decls())
132 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000133 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000134 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000135 }
136
137public:
138 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
139 : CodeGenFunction::RunCleanupsScope(CGF) {
140 emitPreInitStmt(CGF, S);
141 }
142};
143
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000144class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
145 CodeGenFunction::OMPPrivateScope InlinedShareds;
146
147 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
148 return CGF.LambdaCaptureFields.lookup(VD) ||
149 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
150 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
151 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
152 }
153
154public:
155 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
156 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
157 InlinedShareds(CGF) {
158 for (const auto *C : S.clauses()) {
159 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
160 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
161 for (const auto *I : PreInit->decls()) {
162 if (!I->hasAttr<OMPCaptureNoInitAttr>())
163 CGF.EmitVarDecl(cast<VarDecl>(*I));
164 else {
165 CodeGenFunction::AutoVarEmission Emission =
166 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
167 CGF.EmitAutoVarCleanups(Emission);
168 }
169 }
170 }
171 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
172 for (const Expr *E : UDP->varlists()) {
173 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
174 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
175 CGF.EmitVarDecl(*OED);
176 }
177 }
178 }
179 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
180 CGF.EmitOMPPrivateClause(S, InlinedShareds);
181 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
182 if (const Expr *E = TG->getReductionRef())
183 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
184 }
185 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
186 while (CS) {
187 for (auto &C : CS->captures()) {
188 if (C.capturesVariable() || C.capturesVariableByCopy()) {
189 auto *VD = C.getCapturedVar();
190 assert(VD == VD->getCanonicalDecl() &&
191 "Canonical decl must be captured.");
192 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
193 isCapturedVar(CGF, VD) ||
194 (CGF.CapturedStmtInfo &&
195 InlinedShareds.isGlobalVarCaptured(VD)),
196 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000197 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000198 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
199 return CGF.EmitLValue(&DRE).getAddress();
200 });
201 }
202 }
203 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
204 }
205 (void)InlinedShareds.Privatize();
206 }
207};
208
Alexey Bataev3392d762016-02-16 11:18:12 +0000209} // namespace
210
Alexey Bataevf8365372017-11-17 17:57:25 +0000211static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
212 const OMPExecutableDirective &S,
213 const RegionCodeGenTy &CodeGen);
214
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000215LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
216 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
217 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
218 OrigVD = OrigVD->getCanonicalDecl();
219 bool IsCaptured =
220 LambdaCaptureFields.lookup(OrigVD) ||
221 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
222 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
223 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
224 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
225 return EmitLValue(&DRE);
226 }
227 }
228 return EmitLValue(E);
229}
230
Alexey Bataev1189bd02016-01-26 12:20:39 +0000231llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
232 auto &C = getContext();
233 llvm::Value *Size = nullptr;
234 auto SizeInChars = C.getTypeSizeInChars(Ty);
235 if (SizeInChars.isZero()) {
236 // getTypeSizeInChars() returns 0 for a VLA.
237 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +0000238 auto VlaSize = getVLASize(VAT);
239 Ty = VlaSize.Type;
240 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
241 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000242 }
243 SizeInChars = C.getTypeSizeInChars(Ty);
244 if (SizeInChars.isZero())
245 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
246 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
247 } else
248 Size = CGM.getSize(SizeInChars);
249 return Size;
250}
251
Alexey Bataev2377fe92015-09-10 08:12:02 +0000252void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000253 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000254 const RecordDecl *RD = S.getCapturedRecordDecl();
255 auto CurField = RD->field_begin();
256 auto CurCap = S.captures().begin();
257 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
258 E = S.capture_init_end();
259 I != E; ++I, ++CurField, ++CurCap) {
260 if (CurField->hasCapturedVLAType()) {
261 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000262 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000263 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000264 } else if (CurCap->capturesThis())
265 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000266 else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000267 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000268
269 // If the field is not a pointer, we need to save the actual value
270 // and load it as a void pointer.
271 if (!CurField->getType()->isAnyPointerType()) {
272 auto &Ctx = getContext();
273 auto DstAddr = CreateMemTemp(
274 Ctx.getUIntPtrType(),
275 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
276 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
277
278 auto *SrcAddrVal = EmitScalarConversion(
279 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000280 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000281 LValue SrcLV =
282 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
283
284 // Store the value using the source type pointer.
285 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
286
287 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000288 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000289 }
290 CapturedVars.push_back(CV);
291 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000292 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000293 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 }
296}
297
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000298static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
299 QualType DstType, StringRef Name,
300 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000301 bool isReferenceType = false) {
302 ASTContext &Ctx = CGF.getContext();
303
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000304 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
305 Ctx.getUIntPtrType(),
306 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000307 auto TmpAddr =
308 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
309 .getAddress();
310
311 // If we are dealing with references we need to return the address of the
312 // reference instead of the reference of the value.
313 if (isReferenceType) {
314 QualType RefType = Ctx.getLValueReferenceType(DstType);
315 auto *RefVal = TmpAddr.getPointer();
316 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
317 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000318 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000319 }
320
321 return TmpAddr;
322}
323
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000324static QualType getCanonicalParamType(ASTContext &C, QualType T) {
325 if (T->isLValueReferenceType()) {
326 return C.getLValueReferenceType(
327 getCanonicalParamType(C, T.getNonReferenceType()),
328 /*SpelledAsLValue=*/false);
329 }
330 if (T->isPointerType())
331 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000332 if (auto *A = T->getAsArrayTypeUnsafe()) {
333 if (auto *VLA = dyn_cast<VariableArrayType>(A))
334 return getCanonicalParamType(C, VLA->getElementType());
335 else if (!A->isVariablyModifiedType())
336 return C.getCanonicalType(T);
337 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000338 return C.getCanonicalParamType(T);
339}
340
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000341namespace {
342 /// Contains required data for proper outlined function codegen.
343 struct FunctionOptions {
344 /// Captured statement for which the function is generated.
345 const CapturedStmt *S = nullptr;
346 /// true if cast to/from UIntPtr is required for variables captured by
347 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000348 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000349 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000351 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
355 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000356 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000357 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
358 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000359 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 };
361}
362
Alexey Bataeve754b182017-08-09 19:38:53 +0000363static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000364 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000365 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 &LocalAddrs,
367 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
368 &VLASizes,
369 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
370 const CapturedDecl *CD = FO.S->getCapturedDecl();
371 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000372 assert(CD->hasBody() && "missing CapturedDecl body");
373
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000375 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000378 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 Args.append(CD->param_begin(),
380 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000381 TargetArgs.append(
382 CD->param_begin(),
383 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000384 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000385 FunctionDecl *DebugFunctionDecl = nullptr;
386 if (!FO.UIntPtrCastRequired) {
387 FunctionProtoType::ExtProtoInfo EPI;
388 DebugFunctionDecl = FunctionDecl::Create(
389 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
390 SourceLocation(), DeclarationName(), Ctx.VoidTy,
391 Ctx.getTrivialTypeSourceInfo(
392 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
393 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
394 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 for (auto *FD : RD->fields()) {
396 QualType ArgType = FD->getType();
397 IdentifierInfo *II = nullptr;
398 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000399
400 // If this is a capture by copy and the type is not a pointer, the outlined
401 // function argument type should be uintptr and the value properly casted to
402 // uintptr. This is necessary given that the runtime library is only able to
403 // deal with pointers. We can pass in the same way the VLA type sizes to the
404 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000405 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000406 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 if (FO.UIntPtrCastRequired)
408 ArgType = Ctx.getUIntPtrType();
409 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000410
411 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000412 CapVar = I->getCapturedVar();
413 II = CapVar->getIdentifier();
414 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 else {
417 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000418 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000419 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000420 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000421 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000422 VarDecl *Arg;
423 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
424 Arg = ParmVarDecl::Create(
425 Ctx, DebugFunctionDecl,
426 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
427 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
428 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
429 } else {
430 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
431 II, ArgType, ImplicitParamDecl::Other);
432 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000433 Args.emplace_back(Arg);
434 // Do not cast arguments if we emit function with non-original types.
435 TargetArgs.emplace_back(
436 FO.UIntPtrCastRequired
437 ? Arg
438 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000439 ++I;
440 }
441 Args.append(
442 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
443 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000444 TargetArgs.append(
445 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
446 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000447
448 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000449 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000451 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
452
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000453 llvm::Function *F =
454 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
455 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000456 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
457 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000458 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000459
460 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000461 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
462 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000463 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000464 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000466 // Do not map arguments if we emit function with non-original types.
467 Address LocalAddr(Address::invalid());
468 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
469 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
470 TargetArgs[Cnt]);
471 } else {
472 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
473 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000474 // If we are capturing a pointer by copy we don't need to do anything, just
475 // use the value that we get from the arguments.
476 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000477 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000478 // If the variable is a reference we need to materialize it here.
479 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000480 Address RefAddr = CGF.CreateMemTemp(
481 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
482 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
483 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000484 LocalAddr = RefAddr;
485 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000486 if (!FO.RegisterCastedArgsOnly)
487 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000488 ++Cnt;
489 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000490 continue;
491 }
492
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000493 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
494 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000495 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000496 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000497 ArgLVal = CGF.MakeAddrLValue(
498 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
499 Args[Cnt]->getName(), ArgLVal),
500 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 }
Alexey Bataev1e491372018-01-23 18:44:14 +0000502 auto *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000503 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 } else if (I->capturesVariable()) {
506 auto *Var = I->getCapturedVar();
507 QualType VarTy = Var->getType();
508 Address ArgAddr = ArgLVal.getAddress();
509 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000510 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000511 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000512 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000513 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000514 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
516 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000518 if (!FO.RegisterCastedArgsOnly) {
519 LocalAddrs.insert(
520 {Args[Cnt],
521 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
522 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000523 } else if (I->capturesVariableByCopy()) {
524 assert(!FD->getType()->isAnyPointerType() &&
525 "Not expecting a captured pointer.");
526 auto *Var = I->getCapturedVar();
527 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000528 LocalAddrs.insert(
529 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000530 {Var, FO.UIntPtrCastRequired
531 ? castValueFromUintptr(CGF, I->getLocation(),
532 FD->getType(), Args[Cnt]->getName(),
533 ArgLVal, VarTy->isReferenceType())
534 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000535 } else {
536 // If 'this' is captured, load it into CXXThisValue.
537 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000538 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000539 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000540 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000541 ++Cnt;
542 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 }
544
Alexey Bataeve754b182017-08-09 19:38:53 +0000545 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000546}
547
548llvm::Function *
549CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
550 assert(
551 CapturedStmtInfo &&
552 "CapturedStmtInfo should be set when generating the captured function");
553 const CapturedDecl *CD = S.getCapturedDecl();
554 // Build the argument list.
555 bool NeedWrapperFunction =
556 getDebugInfo() &&
557 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
558 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000559 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000560 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000561 SmallString<256> Buffer;
562 llvm::raw_svector_ostream Out(Buffer);
563 Out << CapturedStmtInfo->getHelperName();
564 if (NeedWrapperFunction)
565 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000566 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000567 Out.str());
568 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
569 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000570 for (const auto &LocalAddrPair : LocalAddrs) {
571 if (LocalAddrPair.second.first) {
572 setAddrOfLocalVar(LocalAddrPair.second.first,
573 LocalAddrPair.second.second);
574 }
575 }
576 for (const auto &VLASizePair : VLASizes)
577 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000578 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000579 CapturedStmtInfo->EmitBody(*this, CD->getBody());
580 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000581 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000582 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000583
Alexey Bataevefd884d2017-08-04 21:26:25 +0000584 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000585 /*RegisterCastedArgsOnly=*/true,
586 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000587 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000588 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 Args.clear();
590 LocalAddrs.clear();
591 VLASizes.clear();
592 llvm::Function *WrapperF =
593 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000594 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000595 llvm::SmallVector<llvm::Value *, 4> CallArgs;
596 for (const auto *Arg : Args) {
597 llvm::Value *CallArg;
598 auto I = LocalAddrs.find(Arg);
599 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000600 LValue LV = WrapperCGF.MakeAddrLValue(
601 I->second.second,
602 I->second.first ? I->second.first->getType() : Arg->getType(),
603 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000604 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000605 } else {
606 auto EI = VLASizes.find(Arg);
607 if (EI != VLASizes.end())
608 CallArg = EI->second.second;
609 else {
610 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000611 Arg->getType(),
612 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000613 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000614 }
615 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000616 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
619 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 WrapperCGF.FinishFunction();
621 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000622}
623
Alexey Bataev9959db52014-05-06 10:08:46 +0000624//===----------------------------------------------------------------------===//
625// OpenMP Directive Emission
626//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000627void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address DestAddr, Address SrcAddr, QualType OriginalType,
629 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630 // Perform element-by-element initialization.
631 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000632
633 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000634 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000635 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
636 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
637
638 auto SrcBegin = SrcAddr.getPointer();
639 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
642 // The basic structure here is a while-do loop.
643 auto BodyBB = createBasicBlock("omp.arraycpy.body");
644 auto DoneBB = createBasicBlock("omp.arraycpy.done");
645 auto IsEmpty =
646 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
647 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000648
Alexey Bataev420d45b2015-04-14 05:11:24 +0000649 // Enter the loop body, making that address the current address.
650 auto EntryBB = Builder.GetInsertBlock();
651 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000652
653 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
654
655 llvm::PHINode *SrcElementPHI =
656 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
657 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
658 Address SrcElementCurrent =
659 Address(SrcElementPHI,
660 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
661
662 llvm::PHINode *DestElementPHI =
663 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
664 DestElementPHI->addIncoming(DestBegin, EntryBB);
665 Address DestElementCurrent =
666 Address(DestElementPHI,
667 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000668
Alexey Bataev420d45b2015-04-14 05:11:24 +0000669 // Emit copy.
670 CopyGen(DestElementCurrent, SrcElementCurrent);
671
672 // Shift the address forward by one element.
673 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000674 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000675 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000676 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000677 // Check whether we've reached the end.
678 auto Done =
679 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
680 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000681 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
682 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000683
684 // Done.
685 EmitBlock(DoneBB, /*IsFinished=*/true);
686}
687
John McCall7f416cc2015-09-08 08:05:57 +0000688void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
689 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000690 const VarDecl *SrcVD, const Expr *Copy) {
691 if (OriginalType->isArrayType()) {
692 auto *BO = dyn_cast<BinaryOperator>(Copy);
693 if (BO && BO->getOpcode() == BO_Assign) {
694 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000695 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
696 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
697 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000698 } else {
699 // For arrays with complex element types perform element by element
700 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000701 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000703 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000704 // Working with the single array element, so have to remap
705 // destination and source variables to corresponding array
706 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000707 CodeGenFunction::OMPPrivateScope Remap(*this);
708 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000709 return DestElement;
710 });
711 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000712 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000713 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000714 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000715 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000716 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000717 } else {
718 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000719 CodeGenFunction::OMPPrivateScope Remap(*this);
720 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
721 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 (void)Remap.Privatize();
723 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000724 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726}
727
Alexey Bataev69c62a92015-04-15 04:52:20 +0000728bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
729 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000730 if (!HaveInsertPoint())
731 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000732 bool FirstprivateIsLastprivate = false;
733 llvm::DenseSet<const VarDecl *> Lastprivates;
734 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
735 for (const auto *D : C->varlists())
736 Lastprivates.insert(
737 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
738 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000739 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000740 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
741 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
742 // Force emission of the firstprivate copy if the directive does not emit
743 // outlined function, like omp for, omp simd, omp distribute etc.
744 bool MustEmitFirstprivateCopy =
745 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000746 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000747 auto IRef = C->varlist_begin();
748 auto InitsRef = C->inits().begin();
749 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000750 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000751 bool ThisFirstprivateIsLastprivate =
752 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
753 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000754 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000755 !FD->getType()->isReferenceType()) {
756 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
757 ++IRef;
758 ++InitsRef;
759 continue;
760 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000761 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000762 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000763 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000764 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
765 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
766 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
768 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
769 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000770 LValue OriginalLVal = EmitLValue(&DRE);
771 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000772 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000773 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000774 // Emit VarDecl with copy init for arrays.
775 // Get the address of the original variable captured in current
776 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000777 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000778 auto Emission = EmitAutoVarAlloca(*VD);
779 auto *Init = VD->getInit();
780 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
781 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000782 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(),
783 Type);
784 EmitAggregateAssign(Dest, OriginalLVal, Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000785 } else {
786 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000787 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000788 [this, VDInit, Init](Address DestElement,
789 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000790 // Clean up any temporaries needed by the initialization.
791 RunCleanupsScope InitScope(*this);
792 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000793 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000794 EmitAnyExprToMem(Init, DestElement,
795 Init->getType().getQualifiers(),
796 /*IsInitializer*/ false);
797 LocalDeclMap.erase(VDInit);
798 });
799 }
800 EmitAutoVarCleanups(Emission);
801 return Emission.getAllocatedAddress();
802 });
803 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000804 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000805 // Emit private VarDecl with copy init.
806 // Remap temp VDInit variable to the address of the original
807 // variable
808 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000809 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000810 EmitDecl(*VD);
811 LocalDeclMap.erase(VDInit);
812 return GetAddrOfLocalVar(VD);
813 });
814 }
815 assert(IsRegistered &&
816 "firstprivate var already registered as private");
817 // Silence the warning about unused variable.
818 (void)IsRegistered;
819 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000820 ++IRef;
821 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000822 }
823 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000824 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000825}
826
Alexey Bataev03b340a2014-10-21 03:16:40 +0000827void CodeGenFunction::EmitOMPPrivateClause(
828 const OMPExecutableDirective &D,
829 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000830 if (!HaveInsertPoint())
831 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000832 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000833 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000834 auto IRef = C->varlist_begin();
835 for (auto IInit : C->private_copies()) {
836 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000837 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
838 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
839 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000840 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000841 // Emit private VarDecl with copy init.
842 EmitDecl(*VD);
843 return GetAddrOfLocalVar(VD);
844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
848 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000849 ++IRef;
850 }
851 }
852}
853
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000854bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000855 if (!HaveInsertPoint())
856 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000857 // threadprivate_var1 = master_threadprivate_var1;
858 // operator=(threadprivate_var2, master_threadprivate_var2);
859 // ...
860 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000861 llvm::DenseSet<const VarDecl *> CopiedVars;
862 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000863 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000864 auto IRef = C->varlist_begin();
865 auto ISrcRef = C->source_exprs().begin();
866 auto IDestRef = C->destination_exprs().begin();
867 for (auto *AssignOp : C->assignment_ops()) {
868 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000869 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000870 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000871 // Get the address of the master variable. If we are emitting code with
872 // TLS support, the address is passed from the master as field in the
873 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000874 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000875 if (getLangOpts().OpenMPUseTLS &&
876 getContext().getTargetInfo().isTLSSupported()) {
877 assert(CapturedStmtInfo->lookup(VD) &&
878 "Copyin threadprivates should have been captured!");
879 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
880 VK_LValue, (*IRef)->getExprLoc());
881 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000882 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000883 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000884 MasterAddr =
885 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
886 : CGM.GetAddrOfGlobal(VD),
887 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000888 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000889 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000890 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000891 if (CopiedVars.size() == 1) {
892 // At first check if current thread is a master thread. If it is, no
893 // need to copy data.
894 CopyBegin = createBasicBlock("copyin.not.master");
895 CopyEnd = createBasicBlock("copyin.not.master.end");
896 Builder.CreateCondBr(
897 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000898 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
899 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000900 CopyBegin, CopyEnd);
901 EmitBlock(CopyBegin);
902 }
903 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
904 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000905 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000906 }
907 ++IRef;
908 ++ISrcRef;
909 ++IDestRef;
910 }
911 }
912 if (CopyEnd) {
913 // Exit out of copying procedure for non-master thread.
914 EmitBlock(CopyEnd, /*IsFinished=*/true);
915 return true;
916 }
917 return false;
918}
919
Alexey Bataev38e89532015-04-16 04:54:05 +0000920bool CodeGenFunction::EmitOMPLastprivateClauseInit(
921 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000922 if (!HaveInsertPoint())
923 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000924 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000925 llvm::DenseSet<const VarDecl *> SIMDLCVs;
926 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
927 auto *LoopDirective = cast<OMPLoopDirective>(&D);
928 for (auto *C : LoopDirective->counters()) {
929 SIMDLCVs.insert(
930 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
931 }
932 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000933 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000934 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000935 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000936 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
937 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000938 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000939 auto IRef = C->varlist_begin();
940 auto IDestRef = C->destination_exprs().begin();
941 for (auto *IInit : C->private_copies()) {
942 // Keep the address of the original variable for future update at the end
943 // of the loop.
944 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000945 // Taskloops do not require additional initialization, it is done in
946 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000947 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
948 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000949 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000950 DeclRefExpr DRE(
951 const_cast<VarDecl *>(OrigVD),
952 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
953 OrigVD) != nullptr,
954 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
955 return EmitLValue(&DRE).getAddress();
956 });
957 // Check if the variable is also a firstprivate: in this case IInit is
958 // not generated. Initialization of this variable will happen in codegen
959 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000960 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000961 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000962 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
963 // Emit private VarDecl with copy init.
964 EmitDecl(*VD);
965 return GetAddrOfLocalVar(VD);
966 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000967 assert(IsRegistered &&
968 "lastprivate var already registered as private");
969 (void)IsRegistered;
970 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000971 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000972 ++IRef;
973 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000974 }
975 }
976 return HasAtLeastOneLastprivate;
977}
978
979void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000980 const OMPExecutableDirective &D, bool NoFinals,
981 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000982 if (!HaveInsertPoint())
983 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000984 // Emit following code:
985 // if (<IsLastIterCond>) {
986 // orig_var1 = private_orig_var1;
987 // ...
988 // orig_varn = private_orig_varn;
989 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000990 llvm::BasicBlock *ThenBB = nullptr;
991 llvm::BasicBlock *DoneBB = nullptr;
992 if (IsLastIterCond) {
993 ThenBB = createBasicBlock(".omp.lastprivate.then");
994 DoneBB = createBasicBlock(".omp.lastprivate.done");
995 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
996 EmitBlock(ThenBB);
997 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000998 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
999 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001000 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001001 auto IC = LoopDirective->counters().begin();
1002 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001003 auto *D =
1004 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1005 if (NoFinals)
1006 AlreadyEmittedVars.insert(D);
1007 else
1008 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001009 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001010 }
1011 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001012 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1013 auto IRef = C->varlist_begin();
1014 auto ISrcRef = C->source_exprs().begin();
1015 auto IDestRef = C->destination_exprs().begin();
1016 for (auto *AssignOp : C->assignment_ops()) {
1017 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1018 QualType Type = PrivateVD->getType();
1019 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1020 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1021 // If lastprivate variable is a loop control variable for loop-based
1022 // directive, update its value before copyin back to original
1023 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001024 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1025 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001026 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1027 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1028 // Get the address of the original variable.
1029 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1030 // Get the address of the private variable.
1031 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1032 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1033 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001034 Address(Builder.CreateLoad(PrivateAddr),
1035 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001036 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001037 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001038 ++IRef;
1039 ++ISrcRef;
1040 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001041 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001042 if (auto *PostUpdate = C->getPostUpdateExpr())
1043 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001044 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001045 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001046 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001047}
1048
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001049void CodeGenFunction::EmitOMPReductionClauseInit(
1050 const OMPExecutableDirective &D,
1051 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001052 if (!HaveInsertPoint())
1053 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001054 SmallVector<const Expr *, 4> Shareds;
1055 SmallVector<const Expr *, 4> Privates;
1056 SmallVector<const Expr *, 4> ReductionOps;
1057 SmallVector<const Expr *, 4> LHSs;
1058 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001059 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001060 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001061 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001062 auto ILHS = C->lhs_exprs().begin();
1063 auto IRHS = C->rhs_exprs().begin();
1064 for (const auto *Ref : C->varlists()) {
1065 Shareds.emplace_back(Ref);
1066 Privates.emplace_back(*IPriv);
1067 ReductionOps.emplace_back(*IRed);
1068 LHSs.emplace_back(*ILHS);
1069 RHSs.emplace_back(*IRHS);
1070 std::advance(IPriv, 1);
1071 std::advance(IRed, 1);
1072 std::advance(ILHS, 1);
1073 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001074 }
1075 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001076 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1077 unsigned Count = 0;
1078 auto ILHS = LHSs.begin();
1079 auto IRHS = RHSs.begin();
1080 auto IPriv = Privates.begin();
1081 for (const auto *IRef : Shareds) {
1082 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1083 // Emit private VarDecl with reduction init.
1084 RedCG.emitSharedLValue(*this, Count);
1085 RedCG.emitAggregateType(*this, Count);
1086 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1087 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1088 RedCG.getSharedLValue(Count),
1089 [&Emission](CodeGenFunction &CGF) {
1090 CGF.EmitAutoVarInit(Emission);
1091 return true;
1092 });
1093 EmitAutoVarCleanups(Emission);
1094 Address BaseAddr = RedCG.adjustPrivateAddress(
1095 *this, Count, Emission.getAllocatedAddress());
1096 bool IsRegistered = PrivateScope.addPrivate(
1097 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1098 assert(IsRegistered && "private var already registered as private");
1099 // Silence the warning about unused variable.
1100 (void)IsRegistered;
1101
1102 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1103 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001104 QualType Type = PrivateVD->getType();
1105 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1106 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001107 // Store the address of the original variable associated with the LHS
1108 // implicit variable.
1109 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1110 return RedCG.getSharedLValue(Count).getAddress();
1111 });
1112 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1113 return GetAddrOfLocalVar(PrivateVD);
1114 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001115 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1116 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 // Store the address of the original variable associated with the LHS
1118 // implicit variable.
1119 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1120 return RedCG.getSharedLValue(Count).getAddress();
1121 });
1122 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1123 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1124 ConvertTypeForMem(RHSVD->getType()),
1125 "rhs.begin");
1126 });
1127 } else {
1128 QualType Type = PrivateVD->getType();
1129 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1130 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1131 // Store the address of the original variable associated with the LHS
1132 // implicit variable.
1133 if (IsArray) {
1134 OriginalAddr = Builder.CreateElementBitCast(
1135 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1136 }
1137 PrivateScope.addPrivate(
1138 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1139 PrivateScope.addPrivate(
1140 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1141 return IsArray
1142 ? Builder.CreateElementBitCast(
1143 GetAddrOfLocalVar(PrivateVD),
1144 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1145 : GetAddrOfLocalVar(PrivateVD);
1146 });
1147 }
1148 ++ILHS;
1149 ++IRHS;
1150 ++IPriv;
1151 ++Count;
1152 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001153}
1154
1155void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001156 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001157 if (!HaveInsertPoint())
1158 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001159 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001160 llvm::SmallVector<const Expr *, 8> LHSExprs;
1161 llvm::SmallVector<const Expr *, 8> RHSExprs;
1162 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001163 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001164 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001166 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001167 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1168 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1169 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1170 }
1171 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001172 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1173 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001174 ReductionKind == OMPD_simd;
1175 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001176 // Emit nowait reduction if nowait clause is present or directive is a
1177 // parallel directive (it always has implicit barrier).
1178 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001179 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001180 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001181 }
1182}
1183
Alexey Bataev61205072016-03-02 04:57:40 +00001184static void emitPostUpdateForReductionClause(
1185 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1186 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1187 if (!CGF.HaveInsertPoint())
1188 return;
1189 llvm::BasicBlock *DoneBB = nullptr;
1190 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1191 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1192 if (!DoneBB) {
1193 if (auto *Cond = CondGen(CGF)) {
1194 // If the first post-update expression is found, emit conditional
1195 // block if it was requested.
1196 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1197 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1198 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1199 CGF.EmitBlock(ThenBB);
1200 }
1201 }
1202 CGF.EmitIgnoredExpr(PostUpdate);
1203 }
1204 }
1205 if (DoneBB)
1206 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1207}
1208
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001209namespace {
1210/// Codegen lambda for appending distribute lower and upper bounds to outlined
1211/// parallel function. This is necessary for combined constructs such as
1212/// 'distribute parallel for'
1213typedef llvm::function_ref<void(CodeGenFunction &,
1214 const OMPExecutableDirective &,
1215 llvm::SmallVectorImpl<llvm::Value *> &)>
1216 CodeGenBoundParametersTy;
1217} // anonymous namespace
1218
1219static void emitCommonOMPParallelDirective(
1220 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1221 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1222 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001223 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1224 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1225 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001226 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001227 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001228 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1229 /*IgnoreResultAssign*/ true);
1230 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1231 CGF, NumThreads, NumThreadsClause->getLocStart());
1232 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001233 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001234 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001235 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1236 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1237 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001238 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001239 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1240 if (C->getNameModifier() == OMPD_unknown ||
1241 C->getNameModifier() == OMPD_parallel) {
1242 IfCond = C->getCondition();
1243 break;
1244 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001245 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001246
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001247 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001248 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001249 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1250 // lower and upper bounds with the pragma 'for' chunking mechanism.
1251 // The following lambda takes care of appending the lower and upper bound
1252 // parameters when necessary
1253 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001254 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001255 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001256 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001257}
1258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001259static void emitEmptyBoundParameters(CodeGenFunction &,
1260 const OMPExecutableDirective &,
1261 llvm::SmallVectorImpl<llvm::Value *> &) {}
1262
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001265 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001267 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001268 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1269 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001270 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001271 // propagation master's thread values of threadprivate variables to local
1272 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001273 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1274 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1275 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001276 }
1277 CGF.EmitOMPPrivateClause(S, PrivateScope);
1278 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1279 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001280 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001281 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001283 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1284 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001285 emitPostUpdateForReductionClause(
1286 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001287}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001288
Alexey Bataev0f34da12015-07-02 04:17:07 +00001289void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1290 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001291 RunCleanupsScope BodyScope(*this);
1292 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001293 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001294 EmitIgnoredExpr(I);
1295 }
Alexander Musman3276a272015-03-21 10:12:56 +00001296 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001297 // In distribute directives only loop counters may be marked as linear, no
1298 // need to generate the code for them.
1299 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1301 for (auto *U : C->updates())
1302 EmitIgnoredExpr(U);
1303 }
Alexander Musman3276a272015-03-21 10:12:56 +00001304 }
1305
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001307 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001308 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001311 // The end (updates/cleanups).
1312 EmitBlock(Continue.getBlock());
1313 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314}
1315
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316void CodeGenFunction::EmitOMPInnerLoop(
1317 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1318 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001319 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1320 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001321 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001322
1323 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001324 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001325 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001326 const SourceRange &R = S.getSourceRange();
1327 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1328 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001329
1330 // If there are any cleanups between here and the loop-exit scope,
1331 // create a block to stage a loop exit along.
1332 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001333 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
Alexander Musmand196ef22014-10-07 08:57:09 +00001336 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001337
Alexey Bataev2df54a02015-03-12 08:53:29 +00001338 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001339 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001340 if (ExitBlock != LoopExit.getBlock()) {
1341 EmitBlock(ExitBlock);
1342 EmitBranchThroughCleanup(LoopExit);
1343 }
1344
1345 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001346 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001347
1348 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001349 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001350 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1351
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353
1354 // Emit "IV = IV + 1" and a back-edge to the condition block.
1355 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001356 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001357 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358 BreakContinueStack.pop_back();
1359 EmitBranch(CondBlock);
1360 LoopStack.pop();
1361 // Emit the fall-through block.
1362 EmitBlock(LoopExit.getBlock());
1363}
1364
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001365bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001366 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001369 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001370 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001371 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001372 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001374 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1375 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1376 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1377 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1378 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1379 VD->getInit()->getType(), VK_LValue,
1380 VD->getInit()->getExprLoc());
1381 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1382 VD->getType()),
1383 /*capturedByInit=*/false);
1384 EmitAutoVarCleanups(Emission);
1385 } else
1386 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001387 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001388 // Emit the linear steps for the linear clauses.
1389 // If a step is not constant, it is pre-calculated before the loop.
1390 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1391 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001392 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001394 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001395 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001396 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001397 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001398}
1399
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400void CodeGenFunction::EmitOMPLinearClauseFinal(
1401 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001402 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001403 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001404 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001405 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001406 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001407 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001408 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001410 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001412 // If the first post-update expression is found, emit conditional
1413 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001414 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1415 DoneBB = createBasicBlock(".omp.linear.pu.done");
1416 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1417 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001418 }
1419 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001420 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1421 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001422 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001423 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 Address OrigAddr = EmitLValue(&DRE).getAddress();
1425 CodeGenFunction::OMPPrivateScope VarScope(*this);
1426 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001427 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001428 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001429 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001430 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001431 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001432 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001433 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001434 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001435 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001436}
1437
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001438static void emitAlignedClause(CodeGenFunction &CGF,
1439 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001440 if (!CGF.HaveInsertPoint())
1441 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001442 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001443 unsigned ClauseAlignment = 0;
1444 if (auto AlignmentExpr = Clause->getAlignment()) {
1445 auto AlignmentCI =
1446 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1447 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001448 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001449 for (auto E : Clause->varlists()) {
1450 unsigned Alignment = ClauseAlignment;
1451 if (Alignment == 0) {
1452 // OpenMP [2.8.1, Description]
1453 // If no optional parameter is specified, implementation-defined default
1454 // alignments for SIMD instructions on the target platforms are assumed.
1455 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001456 CGF.getContext()
1457 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1458 E->getType()->getPointeeType()))
1459 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001460 }
1461 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1462 "alignment is not power of 2");
1463 if (Alignment != 0) {
1464 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1465 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1466 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001467 }
1468 }
1469}
1470
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001471void CodeGenFunction::EmitOMPPrivateLoopCounters(
1472 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1473 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001474 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001475 auto I = S.private_counters().begin();
1476 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001477 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1478 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001479 // Emit var without initialization.
1480 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1481 EmitAutoVarCleanups(VarEmission);
1482 LocalDeclMap.erase(PrivateVD);
1483 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1484 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001485 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001486 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1487 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001488 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001489 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1490 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1491 E->getType(), VK_LValue, E->getExprLoc());
1492 return EmitLValue(&DRE).getAddress();
1493 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001494 } else {
1495 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1496 return VarEmission.getAllocatedAddress();
1497 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001498 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001499 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001500 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001501}
1502
Alexey Bataev62dbb972015-04-22 11:59:37 +00001503static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1504 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1505 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001506 if (!CGF.HaveInsertPoint())
1507 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001508 {
1509 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001510 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001511 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001513 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001514 CGF.EmitIgnoredExpr(I);
1515 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001516 }
1517 // Check that loop is executed at least one time.
1518 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1519}
1520
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001521void CodeGenFunction::EmitOMPLinearClause(
1522 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1523 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001524 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001525 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1526 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1527 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1528 for (auto *C : LoopDirective->counters()) {
1529 SIMDLCVs.insert(
1530 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1531 }
1532 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001533 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001534 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001535 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001536 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1537 auto *PrivateVD =
1538 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001539 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1540 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1541 // Emit private VarDecl with copy init.
1542 EmitVarDecl(*PrivateVD);
1543 return GetAddrOfLocalVar(PrivateVD);
1544 });
1545 assert(IsRegistered && "linear var already registered as private");
1546 // Silence the warning about unused variable.
1547 (void)IsRegistered;
1548 } else
1549 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001550 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001551 }
1552 }
1553}
1554
Alexey Bataev45bfad52015-08-21 12:19:04 +00001555static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001556 const OMPExecutableDirective &D,
1557 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001558 if (!CGF.HaveInsertPoint())
1559 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001560 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001561 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1562 /*ignoreResult=*/true);
1563 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1564 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1565 // In presence of finite 'safelen', it may be unsafe to mark all
1566 // the memory instructions parallel, because loop-carried
1567 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001568 if (!IsMonotonic)
1569 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001570 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001571 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1572 /*ignoreResult=*/true);
1573 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001574 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001575 // In presence of finite 'safelen', it may be unsafe to mark all
1576 // the memory instructions parallel, because loop-carried
1577 // dependences of 'safelen' iterations are possible.
1578 CGF.LoopStack.setParallel(false);
1579 }
1580}
1581
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001582void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1583 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001584 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001585 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001586 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001587 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001588}
1589
Alexey Bataevef549a82016-03-09 09:49:09 +00001590void CodeGenFunction::EmitOMPSimdFinal(
1591 const OMPLoopDirective &D,
1592 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001593 if (!HaveInsertPoint())
1594 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001595 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001596 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001597 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001598 for (auto F : D.finals()) {
1599 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001600 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1601 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1602 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1603 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001604 if (!DoneBB) {
1605 if (auto *Cond = CondGen(*this)) {
1606 // If the first post-update expression is found, emit conditional
1607 // block if it was requested.
1608 auto *ThenBB = createBasicBlock(".omp.final.then");
1609 DoneBB = createBasicBlock(".omp.final.done");
1610 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1611 EmitBlock(ThenBB);
1612 }
1613 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001614 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001615 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001616 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001617 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001618 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1619 /*RefersToEnclosingVariableOrCapture=*/false,
1620 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1621 OrigAddr = EmitLValue(&DRE).getAddress();
1622 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001623 OMPPrivateScope VarScope(*this);
1624 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001625 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001626 (void)VarScope.Privatize();
1627 EmitIgnoredExpr(F);
1628 }
1629 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001630 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001631 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001632 if (DoneBB)
1633 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001634}
1635
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001636static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1637 const OMPLoopDirective &S,
1638 CodeGenFunction::JumpDest LoopExit) {
1639 CGF.EmitOMPLoopBody(S, LoopExit);
1640 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001641}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001642
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001643/// Emit a helper variable and return corresponding lvalue.
1644static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1645 const DeclRefExpr *Helper) {
1646 auto VDecl = cast<VarDecl>(Helper->getDecl());
1647 CGF.EmitVarDecl(*VDecl);
1648 return CGF.EmitLValue(Helper);
1649}
1650
Alexey Bataevf8365372017-11-17 17:57:25 +00001651static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1652 PrePostActionTy &Action) {
1653 Action.Enter(CGF);
1654 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1655 "Expected simd directive");
1656 OMPLoopScope PreInitScope(CGF, S);
1657 // if (PreCond) {
1658 // for (IV in 0..LastIteration) BODY;
1659 // <Final counter/linear vars updates>;
1660 // }
1661 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001662 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1663 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1664 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1665 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1666 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1667 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001668
Alexey Bataevf8365372017-11-17 17:57:25 +00001669 // Emit: if (PreCond) - begin.
1670 // If the condition constant folds and can be elided, avoid emitting the
1671 // whole loop.
1672 bool CondConstant;
1673 llvm::BasicBlock *ContBlock = nullptr;
1674 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1675 if (!CondConstant)
1676 return;
1677 } else {
1678 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1679 ContBlock = CGF.createBasicBlock("simd.if.end");
1680 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1681 CGF.getProfileCount(&S));
1682 CGF.EmitBlock(ThenBlock);
1683 CGF.incrementProfileCounter(&S);
1684 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001685
Alexey Bataevf8365372017-11-17 17:57:25 +00001686 // Emit the loop iteration variable.
1687 const Expr *IVExpr = S.getIterationVariable();
1688 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1689 CGF.EmitVarDecl(*IVDecl);
1690 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001691
Alexey Bataevf8365372017-11-17 17:57:25 +00001692 // Emit the iterations count variable.
1693 // If it is not a variable, Sema decided to calculate iterations count on
1694 // each iteration (e.g., it is foldable into a constant).
1695 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1696 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1697 // Emit calculation of the iterations count.
1698 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1699 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001700
Alexey Bataevf8365372017-11-17 17:57:25 +00001701 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001702
Alexey Bataevf8365372017-11-17 17:57:25 +00001703 emitAlignedClause(CGF, S);
1704 (void)CGF.EmitOMPLinearClauseInit(S);
1705 {
1706 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1707 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1708 CGF.EmitOMPLinearClause(S, LoopScope);
1709 CGF.EmitOMPPrivateClause(S, LoopScope);
1710 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1711 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1712 (void)LoopScope.Privatize();
1713 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1714 S.getInc(),
1715 [&S](CodeGenFunction &CGF) {
1716 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1717 CGF.EmitStopPoint(&S);
1718 },
1719 [](CodeGenFunction &) {});
1720 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001721 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001722 // Emit final copy of the lastprivate variables at the end of loops.
1723 if (HasLastprivateClause)
1724 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1725 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1726 emitPostUpdateForReductionClause(
1727 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1728 }
1729 CGF.EmitOMPLinearClauseFinal(
1730 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1731 // Emit: if (PreCond) - end.
1732 if (ContBlock) {
1733 CGF.EmitBranch(ContBlock);
1734 CGF.EmitBlock(ContBlock, true);
1735 }
1736}
1737
1738void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1739 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1740 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001741 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001742 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001743 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001744}
1745
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001746void CodeGenFunction::EmitOMPOuterLoop(
1747 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1748 CodeGenFunction::OMPPrivateScope &LoopScope,
1749 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1750 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1751 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001753
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001754 const Expr *IVExpr = S.getIterationVariable();
1755 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1756 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1757
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001758 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1759
1760 // Start the loop with a block that tests the condition.
1761 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1762 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001763 const SourceRange &R = S.getSourceRange();
1764 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1765 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001766
1767 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001768 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001769 // UB = min(UB, GlobalUB) or
1770 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1771 // 'distribute parallel for')
1772 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001773 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001774 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001775 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001776 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001777 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001778 BoolCondVal =
1779 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1780 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001781 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001782
1783 // If there are any cleanups between here and the loop-exit scope,
1784 // create a block to stage a loop exit along.
1785 auto ExitBlock = LoopExit.getBlock();
1786 if (LoopScope.requiresCleanups())
1787 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1788
1789 auto LoopBody = createBasicBlock("omp.dispatch.body");
1790 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1791 if (ExitBlock != LoopExit.getBlock()) {
1792 EmitBlock(ExitBlock);
1793 EmitBranchThroughCleanup(LoopExit);
1794 }
1795 EmitBlock(LoopBody);
1796
Alexander Musman92bdaab2015-03-12 13:37:50 +00001797 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1798 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001799 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001800 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001801
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001802 // Create a block for the increment.
1803 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1804 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1805
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001806 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1807 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001808 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1809 LoopStack.setParallel(!IsMonotonic);
1810 else
1811 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001812
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001813 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001814
1815 // when 'distribute' is not combined with a 'for':
1816 // while (idx <= UB) { BODY; ++idx; }
1817 // when 'distribute' is combined with a 'for'
1818 // (e.g. 'distribute parallel for')
1819 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1820 EmitOMPInnerLoop(
1821 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1822 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1823 CodeGenLoop(CGF, S, LoopExit);
1824 },
1825 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1826 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1827 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001828
1829 EmitBlock(Continue.getBlock());
1830 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001831 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001832 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001833 EmitIgnoredExpr(LoopArgs.NextLB);
1834 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001835 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001836
1837 EmitBranch(CondBlock);
1838 LoopStack.pop();
1839 // Emit the fall-through block.
1840 EmitBlock(LoopExit.getBlock());
1841
1842 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001843 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1844 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001845 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1846 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001847 };
1848 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001849}
1850
1851void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001852 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001853 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001854 const OMPLoopArguments &LoopArgs,
1855 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001856 auto &RT = CGM.getOpenMPRuntime();
1857
1858 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001859 const bool DynamicOrOrdered =
1860 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001861
1862 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001863 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001864 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001865 "static non-chunked schedule does not need outer loop");
1866
1867 // Emit outer loop.
1868 //
1869 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1870 // When schedule(dynamic,chunk_size) is specified, the iterations are
1871 // distributed to threads in the team in chunks as the threads request them.
1872 // Each thread executes a chunk of iterations, then requests another chunk,
1873 // until no chunks remain to be distributed. Each chunk contains chunk_size
1874 // iterations, except for the last chunk to be distributed, which may have
1875 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1876 //
1877 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1878 // to threads in the team in chunks as the executing threads request them.
1879 // Each thread executes a chunk of iterations, then requests another chunk,
1880 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1881 // each chunk is proportional to the number of unassigned iterations divided
1882 // by the number of threads in the team, decreasing to 1. For a chunk_size
1883 // with value k (greater than 1), the size of each chunk is determined in the
1884 // same way, with the restriction that the chunks do not contain fewer than k
1885 // iterations (except for the last chunk to be assigned, which may have fewer
1886 // than k iterations).
1887 //
1888 // When schedule(auto) is specified, the decision regarding scheduling is
1889 // delegated to the compiler and/or runtime system. The programmer gives the
1890 // implementation the freedom to choose any possible mapping of iterations to
1891 // threads in the team.
1892 //
1893 // When schedule(runtime) is specified, the decision regarding scheduling is
1894 // deferred until run time, and the schedule and chunk size are taken from the
1895 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1896 // implementation defined
1897 //
1898 // while(__kmpc_dispatch_next(&LB, &UB)) {
1899 // idx = LB;
1900 // while (idx <= UB) { BODY; ++idx;
1901 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1902 // } // inner loop
1903 // }
1904 //
1905 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1906 // When schedule(static, chunk_size) is specified, iterations are divided into
1907 // chunks of size chunk_size, and the chunks are assigned to the threads in
1908 // the team in a round-robin fashion in the order of the thread number.
1909 //
1910 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1911 // while (idx <= UB) { BODY; ++idx; } // inner loop
1912 // LB = LB + ST;
1913 // UB = UB + ST;
1914 // }
1915 //
1916
1917 const Expr *IVExpr = S.getIterationVariable();
1918 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1919 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1920
1921 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001922 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1923 llvm::Value *LBVal = DispatchBounds.first;
1924 llvm::Value *UBVal = DispatchBounds.second;
1925 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1926 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001927 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001928 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001929 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001930 CGOpenMPRuntime::StaticRTInput StaticInit(
1931 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1932 LoopArgs.ST, LoopArgs.Chunk);
1933 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1934 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001935 }
1936
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001937 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1938 const unsigned IVSize,
1939 const bool IVSigned) {
1940 if (Ordered) {
1941 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1942 IVSigned);
1943 }
1944 };
1945
1946 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1947 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1948 OuterLoopArgs.IncExpr = S.getInc();
1949 OuterLoopArgs.Init = S.getInit();
1950 OuterLoopArgs.Cond = S.getCond();
1951 OuterLoopArgs.NextLB = S.getNextLowerBound();
1952 OuterLoopArgs.NextUB = S.getNextUpperBound();
1953 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1954 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001955}
1956
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001957static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1958 const unsigned IVSize, const bool IVSigned) {}
1959
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001960void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001961 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1962 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1963 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001964
1965 auto &RT = CGM.getOpenMPRuntime();
1966
1967 // Emit outer loop.
1968 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1969 // dynamic
1970 //
1971
1972 const Expr *IVExpr = S.getIterationVariable();
1973 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1974 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1975
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001976 CGOpenMPRuntime::StaticRTInput StaticInit(
1977 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1978 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1979 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001980
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001981 // for combined 'distribute' and 'for' the increment expression of distribute
1982 // is store in DistInc. For 'distribute' alone, it is in Inc.
1983 Expr *IncExpr;
1984 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1985 IncExpr = S.getDistInc();
1986 else
1987 IncExpr = S.getInc();
1988
1989 // this routine is shared by 'omp distribute parallel for' and
1990 // 'omp distribute': select the right EUB expression depending on the
1991 // directive
1992 OMPLoopArguments OuterLoopArgs;
1993 OuterLoopArgs.LB = LoopArgs.LB;
1994 OuterLoopArgs.UB = LoopArgs.UB;
1995 OuterLoopArgs.ST = LoopArgs.ST;
1996 OuterLoopArgs.IL = LoopArgs.IL;
1997 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1998 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1999 ? S.getCombinedEnsureUpperBound()
2000 : S.getEnsureUpperBound();
2001 OuterLoopArgs.IncExpr = IncExpr;
2002 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2003 ? S.getCombinedInit()
2004 : S.getInit();
2005 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2006 ? S.getCombinedCond()
2007 : S.getCond();
2008 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2009 ? S.getCombinedNextLowerBound()
2010 : S.getNextLowerBound();
2011 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2012 ? S.getCombinedNextUpperBound()
2013 : S.getNextUpperBound();
2014
2015 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2016 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2017 emitEmptyOrdered);
2018}
2019
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002020static std::pair<LValue, LValue>
2021emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2022 const OMPExecutableDirective &S) {
2023 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2024 LValue LB =
2025 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2026 LValue UB =
2027 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2028
2029 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2030 // parallel for') we need to use the 'distribute'
2031 // chunk lower and upper bounds rather than the whole loop iteration
2032 // space. These are parameters to the outlined function for 'parallel'
2033 // and we copy the bounds of the previous schedule into the
2034 // the current ones.
2035 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2036 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002037 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2038 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002039 PrevLBVal = CGF.EmitScalarConversion(
2040 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002041 LS.getIterationVariable()->getType(),
2042 LS.getPrevLowerBoundVariable()->getExprLoc());
2043 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2044 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002045 PrevUBVal = CGF.EmitScalarConversion(
2046 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002047 LS.getIterationVariable()->getType(),
2048 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002049
2050 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2051 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2052
2053 return {LB, UB};
2054}
2055
2056/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2057/// we need to use the LB and UB expressions generated by the worksharing
2058/// code generation support, whereas in non combined situations we would
2059/// just emit 0 and the LastIteration expression
2060/// This function is necessary due to the difference of the LB and UB
2061/// types for the RT emission routines for 'for_static_init' and
2062/// 'for_dispatch_init'
2063static std::pair<llvm::Value *, llvm::Value *>
2064emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2065 const OMPExecutableDirective &S,
2066 Address LB, Address UB) {
2067 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2068 const Expr *IVExpr = LS.getIterationVariable();
2069 // when implementing a dynamic schedule for a 'for' combined with a
2070 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2071 // is not normalized as each team only executes its own assigned
2072 // distribute chunk
2073 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002074 llvm::Value *LBVal =
2075 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2076 llvm::Value *UBVal =
2077 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002078 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002079}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002080
2081static void emitDistributeParallelForDistributeInnerBoundParams(
2082 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2083 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2084 const auto &Dir = cast<OMPLoopDirective>(S);
2085 LValue LB =
2086 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2087 auto LBCast = CGF.Builder.CreateIntCast(
2088 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2089 CapturedVars.push_back(LBCast);
2090 LValue UB =
2091 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2092
2093 auto UBCast = CGF.Builder.CreateIntCast(
2094 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2095 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002096}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002097
2098static void
2099emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2100 const OMPLoopDirective &S,
2101 CodeGenFunction::JumpDest LoopExit) {
2102 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2103 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002104 bool HasCancel = false;
2105 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2106 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2107 HasCancel = D->hasCancel();
2108 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2109 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002110 else if (const auto *D =
2111 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2112 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002113 }
2114 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2115 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2117 emitDistributeParallelForInnerBounds,
2118 emitDistributeParallelForDispatchBounds);
2119 };
2120
2121 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002122 CGF, S,
2123 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2124 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002125 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002126}
2127
Carlo Bertolli9925f152016-06-27 14:55:37 +00002128void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2129 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002130 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2131 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2132 S.getDistInc());
2133 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002134 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002135 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002136}
2137
Kelvin Li4a39add2016-07-05 05:00:15 +00002138void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2139 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002140 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2141 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2142 S.getDistInc());
2143 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002144 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002145 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002146}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002147
2148void CodeGenFunction::EmitOMPDistributeSimdDirective(
2149 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002150 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2151 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2152 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002153 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002154 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002155}
2156
Alexey Bataevf8365372017-11-17 17:57:25 +00002157void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2158 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2159 // Emit SPMD target parallel for region as a standalone region.
2160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2161 emitOMPSimdRegion(CGF, S, Action);
2162 };
2163 llvm::Function *Fn;
2164 llvm::Constant *Addr;
2165 // Emit target region as a standalone region.
2166 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2167 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2168 assert(Fn && Addr && "Target device function emission failed.");
2169}
2170
Kelvin Li986330c2016-07-20 22:57:10 +00002171void CodeGenFunction::EmitOMPTargetSimdDirective(
2172 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002173 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2174 emitOMPSimdRegion(CGF, S, Action);
2175 };
2176 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002177}
2178
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002179namespace {
2180 struct ScheduleKindModifiersTy {
2181 OpenMPScheduleClauseKind Kind;
2182 OpenMPScheduleClauseModifier M1;
2183 OpenMPScheduleClauseModifier M2;
2184 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2185 OpenMPScheduleClauseModifier M1,
2186 OpenMPScheduleClauseModifier M2)
2187 : Kind(Kind), M1(M1), M2(M2) {}
2188 };
2189} // namespace
2190
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002191bool CodeGenFunction::EmitOMPWorksharingLoop(
2192 const OMPLoopDirective &S, Expr *EUB,
2193 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2194 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 // Emit the loop iteration variable.
2196 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2197 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2198 EmitVarDecl(*IVDecl);
2199
2200 // Emit the iterations count variable.
2201 // If it is not a variable, Sema decided to calculate iterations count on each
2202 // iteration (e.g., it is foldable into a constant).
2203 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2204 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2205 // Emit calculation of the iterations count.
2206 EmitIgnoredExpr(S.getCalcLastIteration());
2207 }
2208
2209 auto &RT = CGM.getOpenMPRuntime();
2210
Alexey Bataev38e89532015-04-16 04:54:05 +00002211 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002212 // Check pre-condition.
2213 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002214 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002215 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002216 // If the condition constant folds and can be elided, avoid emitting the
2217 // whole loop.
2218 bool CondConstant;
2219 llvm::BasicBlock *ContBlock = nullptr;
2220 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2221 if (!CondConstant)
2222 return false;
2223 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002224 auto *ThenBlock = createBasicBlock("omp.precond.then");
2225 ContBlock = createBasicBlock("omp.precond.end");
2226 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002227 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002228 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002229 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002230 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002231
Alexey Bataevea33dee2018-02-15 23:39:43 +00002232 RunCleanupsScope DoacrossCleanupScope(*this);
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 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002369 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002370 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002371 if (ContBlock) {
2372 EmitBranch(ContBlock);
2373 EmitBlock(ContBlock, true);
2374 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002375 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002376 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002377}
2378
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002379/// The following two functions generate expressions for the loop lower
2380/// and upper bounds in case of static and dynamic (dispatch) schedule
2381/// of the associated 'for' or 'distribute' loop.
2382static std::pair<LValue, LValue>
2383emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2384 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2385 LValue LB =
2386 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2387 LValue UB =
2388 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2389 return {LB, UB};
2390}
2391
2392/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2393/// consider the lower and upper bound expressions generated by the
2394/// worksharing loop support, but we use 0 and the iteration space size as
2395/// constants
2396static std::pair<llvm::Value *, llvm::Value *>
2397emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2398 Address LB, Address UB) {
2399 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2400 const Expr *IVExpr = LS.getIterationVariable();
2401 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2402 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2403 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2404 return {LBVal, UBVal};
2405}
2406
Alexander Musmanc6388682014-12-15 07:07:06 +00002407void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002408 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002409 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2410 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002411 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002412 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2413 emitForLoopBounds,
2414 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002416 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002417 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002418 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2419 S.hasCancel());
2420 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002421
2422 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002423 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002424 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2425 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002426}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002427
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002428void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002429 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2431 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002432 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2433 emitForLoopBounds,
2434 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002435 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002436 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002437 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002438 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2439 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002440
2441 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002442 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002443 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2444 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002445}
2446
Alexey Bataev2df54a02015-03-12 08:53:29 +00002447static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2448 const Twine &Name,
2449 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002450 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002451 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002452 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002453 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002454}
2455
Alexey Bataev3392d762016-02-16 11:18:12 +00002456void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002457 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2458 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002459 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2461 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002462 auto &C = CGF.CGM.getContext();
2463 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2464 // Emit helper vars inits.
2465 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2466 CGF.Builder.getInt32(0));
2467 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2468 : CGF.Builder.getInt32(0);
2469 LValue UB =
2470 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2471 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2472 CGF.Builder.getInt32(1));
2473 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2474 CGF.Builder.getInt32(0));
2475 // Loop counter.
2476 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2477 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2478 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2479 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2480 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2481 // Generate condition for loop.
2482 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002483 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002484 // Increment for loop counter.
2485 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002486 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002487 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2488 // Iterate through all sections and emit a switch construct:
2489 // switch (IV) {
2490 // case 0:
2491 // <SectionStmt[0]>;
2492 // break;
2493 // ...
2494 // case <NumSection> - 1:
2495 // <SectionStmt[<NumSection> - 1]>;
2496 // break;
2497 // }
2498 // .omp.sections.exit:
2499 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002500 auto *SwitchStmt =
2501 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2502 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002503 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002504 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002505 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002506 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2507 CGF.EmitBlock(CaseBB);
2508 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002509 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002510 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002511 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002512 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002513 } else {
2514 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2515 CGF.EmitBlock(CaseBB);
2516 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2517 CGF.EmitStmt(Stmt);
2518 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002519 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002520 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002521 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002522
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002523 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2524 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002525 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002526 // initialization of firstprivate variables and post-update of lastprivate
2527 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002528 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2529 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2530 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002531 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002532 CGF.EmitOMPPrivateClause(S, LoopScope);
2533 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2534 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2535 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002536
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002537 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002538 OpenMPScheduleTy ScheduleKind;
2539 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002540 CGOpenMPRuntime::StaticRTInput StaticInit(
2541 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2542 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002543 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002544 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002545 // UB = min(UB, GlobalUB);
2546 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2547 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2548 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2549 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2550 // IV = LB;
2551 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2552 // while (idx <= UB) { BODY; ++idx; }
2553 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2554 [](CodeGenFunction &) {});
2555 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002556 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002557 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2558 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002559 };
2560 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002561 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002562 // Emit post-update of the reduction variables if IsLastIter != 0.
2563 emitPostUpdateForReductionClause(
2564 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2565 return CGF.Builder.CreateIsNotNull(
2566 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2567 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002568
2569 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2570 if (HasLastprivates)
2571 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002572 S, /*NoFinals=*/false,
2573 CGF.Builder.CreateIsNotNull(
2574 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002575 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002576
2577 bool HasCancel = false;
2578 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2579 HasCancel = OSD->hasCancel();
2580 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2581 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002582 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002583 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2584 HasCancel);
2585 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2586 // clause. Otherwise the barrier will be generated by the codegen for the
2587 // directive.
2588 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002589 // Emit implicit barrier to synchronize threads and avoid data races on
2590 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002591 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2592 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002593 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002594}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002595
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002596void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002597 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002598 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002599 EmitSections(S);
2600 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002601 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002602 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002603 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2604 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002605 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002606}
2607
2608void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002609 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002610 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002611 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002612 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002613 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2614 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002615}
2616
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002617void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002618 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002619 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002620 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002621 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002622 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002623 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002624 // Build a list of copyprivate variables along with helper expressions
2625 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002626 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002627 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002628 DestExprs.append(C->destination_exprs().begin(),
2629 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002630 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002631 AssignmentOps.append(C->assignment_ops().begin(),
2632 C->assignment_ops().end());
2633 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002634 // Emit code for 'single' region along with 'copyprivate' clauses
2635 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2636 Action.Enter(CGF);
2637 OMPPrivateScope SingleScope(CGF);
2638 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2639 CGF.EmitOMPPrivateClause(S, SingleScope);
2640 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002641 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002642 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002643 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002644 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002645 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2646 CopyprivateVars, DestExprs,
2647 SrcExprs, AssignmentOps);
2648 }
2649 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2650 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002651 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002652 CGM.getOpenMPRuntime().emitBarrierCall(
2653 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002654 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002655 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002656}
2657
Alexey Bataev8d690652014-12-04 07:23:53 +00002658void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002659 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2660 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002661 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002662 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002663 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002665}
2666
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002667void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002668 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2669 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002670 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002671 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002672 Expr *Hint = nullptr;
2673 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2674 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002675 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002676 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2677 S.getDirectiveName().getAsString(),
2678 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002679}
2680
Alexey Bataev671605e2015-04-13 05:28:11 +00002681void CodeGenFunction::EmitOMPParallelForDirective(
2682 const OMPParallelForDirective &S) {
2683 // Emit directive as a combined directive that consists of two implicit
2684 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002685 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002686 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002687 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2688 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002689 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002690 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2691 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002692}
2693
Alexander Musmane4e893b2014-09-23 09:33:00 +00002694void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002695 const OMPParallelForSimdDirective &S) {
2696 // Emit directive as a combined directive that consists of two implicit
2697 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002698 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002699 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2700 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002701 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002702 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2703 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002704}
2705
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002706void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002707 const OMPParallelSectionsDirective &S) {
2708 // Emit directive as a combined directive that consists of two implicit
2709 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002710 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2711 CGF.EmitSections(S);
2712 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002713 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2714 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002715}
2716
Alexey Bataev475a7442018-01-12 19:39:11 +00002717void CodeGenFunction::EmitOMPTaskBasedDirective(
2718 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2719 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2720 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002721 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002722 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002723 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002724 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002725 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002726 // Check if the task is final
2727 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2728 // If the condition constant folds and can be elided, try to avoid emitting
2729 // the condition and the dead arm of the if/else.
2730 auto *Cond = Clause->getCondition();
2731 bool CondConstant;
2732 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2733 Data.Final.setInt(CondConstant);
2734 else
2735 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2736 } else {
2737 // By default the task is not final.
2738 Data.Final.setInt(/*IntVal=*/false);
2739 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002740 // Check if the task has 'priority' clause.
2741 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002742 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002743 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002744 Data.Priority.setPointer(EmitScalarConversion(
2745 EmitScalarExpr(Prio), Prio->getType(),
2746 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2747 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002748 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002749 // The first function argument for tasks is a thread id, the second one is a
2750 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002751 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2752 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002753 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002754 auto IRef = C->varlist_begin();
2755 for (auto *IInit : C->private_copies()) {
2756 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2757 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002758 Data.PrivateVars.push_back(*IRef);
2759 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002760 }
2761 ++IRef;
2762 }
2763 }
2764 EmittedAsPrivate.clear();
2765 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002766 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002767 auto IRef = C->varlist_begin();
2768 auto IElemInitRef = C->inits().begin();
2769 for (auto *IInit : C->private_copies()) {
2770 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2771 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002772 Data.FirstprivateVars.push_back(*IRef);
2773 Data.FirstprivateCopies.push_back(IInit);
2774 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002775 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002776 ++IRef;
2777 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002778 }
2779 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002780 // Get list of lastprivate variables (for taskloops).
2781 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2782 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2783 auto IRef = C->varlist_begin();
2784 auto ID = C->destination_exprs().begin();
2785 for (auto *IInit : C->private_copies()) {
2786 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2787 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2788 Data.LastprivateVars.push_back(*IRef);
2789 Data.LastprivateCopies.push_back(IInit);
2790 }
2791 LastprivateDstsOrigs.insert(
2792 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2793 cast<DeclRefExpr>(*IRef)});
2794 ++IRef;
2795 ++ID;
2796 }
2797 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002798 SmallVector<const Expr *, 4> LHSs;
2799 SmallVector<const Expr *, 4> RHSs;
2800 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2801 auto IPriv = C->privates().begin();
2802 auto IRed = C->reduction_ops().begin();
2803 auto ILHS = C->lhs_exprs().begin();
2804 auto IRHS = C->rhs_exprs().begin();
2805 for (const auto *Ref : C->varlists()) {
2806 Data.ReductionVars.emplace_back(Ref);
2807 Data.ReductionCopies.emplace_back(*IPriv);
2808 Data.ReductionOps.emplace_back(*IRed);
2809 LHSs.emplace_back(*ILHS);
2810 RHSs.emplace_back(*IRHS);
2811 std::advance(IPriv, 1);
2812 std::advance(IRed, 1);
2813 std::advance(ILHS, 1);
2814 std::advance(IRHS, 1);
2815 }
2816 }
2817 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2818 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002819 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002820 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2821 for (auto *IRef : C->varlists())
2822 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002823 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2824 CapturedRegion](CodeGenFunction &CGF,
2825 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002826 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002827 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002828 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2829 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002830 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002831 auto *CopyFn = CGF.Builder.CreateLoad(
2832 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2833 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2834 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2835 // Map privates.
2836 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2837 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2838 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002839 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002840 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2841 Address PrivatePtr = CGF.CreateMemTemp(
2842 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2843 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2844 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002845 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002846 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002847 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2848 Address PrivatePtr =
2849 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2850 ".firstpriv.ptr.addr");
2851 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2852 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002853 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002854 for (auto *E : Data.LastprivateVars) {
2855 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2856 Address PrivatePtr =
2857 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2858 ".lastpriv.ptr.addr");
2859 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2860 CallArgs.push_back(PrivatePtr.getPointer());
2861 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002862 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2863 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002864 for (auto &&Pair : LastprivateDstsOrigs) {
2865 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2866 DeclRefExpr DRE(
2867 const_cast<VarDecl *>(OrigVD),
2868 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2869 OrigVD) != nullptr,
2870 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2871 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2872 return CGF.EmitLValue(&DRE).getAddress();
2873 });
2874 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002875 for (auto &&Pair : PrivatePtrs) {
2876 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2877 CGF.getContext().getDeclAlign(Pair.first));
2878 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2879 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002880 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002881 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002882 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002883 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2884 Data.ReductionOps);
2885 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2886 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2887 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2888 RedCG.emitSharedLValue(CGF, Cnt);
2889 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002890 // FIXME: This must removed once the runtime library is fixed.
2891 // Emit required threadprivate variables for
2892 // initilizer/combiner/finalizer.
2893 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2894 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002895 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2896 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2897 Replacement =
2898 Address(CGF.EmitScalarConversion(
2899 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2900 CGF.getContext().getPointerType(
2901 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002902 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002903 Replacement.getAlignment());
2904 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2905 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2906 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002907 }
2908 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002909 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002910 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002911 SmallVector<const Expr *, 4> InRedVars;
2912 SmallVector<const Expr *, 4> InRedPrivs;
2913 SmallVector<const Expr *, 4> InRedOps;
2914 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2915 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2916 auto IPriv = C->privates().begin();
2917 auto IRed = C->reduction_ops().begin();
2918 auto ITD = C->taskgroup_descriptors().begin();
2919 for (const auto *Ref : C->varlists()) {
2920 InRedVars.emplace_back(Ref);
2921 InRedPrivs.emplace_back(*IPriv);
2922 InRedOps.emplace_back(*IRed);
2923 TaskgroupDescriptors.emplace_back(*ITD);
2924 std::advance(IPriv, 1);
2925 std::advance(IRed, 1);
2926 std::advance(ITD, 1);
2927 }
2928 }
2929 // Privatize in_reduction items here, because taskgroup descriptors must be
2930 // privatized earlier.
2931 OMPPrivateScope InRedScope(CGF);
2932 if (!InRedVars.empty()) {
2933 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2934 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2935 RedCG.emitSharedLValue(CGF, Cnt);
2936 RedCG.emitAggregateType(CGF, Cnt);
2937 // The taskgroup descriptor variable is always implicit firstprivate and
2938 // privatized already during procoessing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002939 // FIXME: This must removed once the runtime library is fixed.
2940 // Emit required threadprivate variables for
2941 // initilizer/combiner/finalizer.
2942 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2943 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002944 llvm::Value *ReductionsPtr =
2945 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2946 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002947 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2948 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2949 Replacement = Address(
2950 CGF.EmitScalarConversion(
2951 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2952 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002953 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002954 Replacement.getAlignment());
2955 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2956 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2957 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00002958 }
2959 }
2960 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002961
2962 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002963 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002964 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002965 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2966 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2967 Data.NumberOfParts);
2968 OMPLexicalScope Scope(*this, S);
2969 TaskGen(*this, OutlinedFn, Data);
2970}
2971
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002972static ImplicitParamDecl *
2973createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002974 QualType Ty, CapturedDecl *CD,
2975 SourceLocation Loc) {
2976 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2977 ImplicitParamDecl::Other);
2978 auto *OrigRef = DeclRefExpr::Create(
2979 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2980 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2981 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2982 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002983 auto *PrivateRef = DeclRefExpr::Create(
2984 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002985 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002986 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002987 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2988 ImplicitParamDecl::Other);
2989 auto *InitRef = DeclRefExpr::Create(
2990 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2991 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002992 PrivateVD->setInitStyle(VarDecl::CInit);
2993 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2994 InitRef, /*BasePath=*/nullptr,
2995 VK_RValue));
2996 Data.FirstprivateVars.emplace_back(OrigRef);
2997 Data.FirstprivateCopies.emplace_back(PrivateRef);
2998 Data.FirstprivateInits.emplace_back(InitRef);
2999 return OrigVD;
3000}
3001
3002void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3003 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3004 OMPTargetDataInfo &InputInfo) {
3005 // Emit outlined function for task construct.
3006 auto CS = S.getCapturedStmt(OMPD_task);
3007 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3008 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3009 auto *I = CS->getCapturedDecl()->param_begin();
3010 auto *PartId = std::next(I);
3011 auto *TaskT = std::next(I, 4);
3012 OMPTaskDataTy Data;
3013 // The task is not final.
3014 Data.Final.setInt(/*IntVal=*/false);
3015 // Get list of firstprivate variables.
3016 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3017 auto IRef = C->varlist_begin();
3018 auto IElemInitRef = C->inits().begin();
3019 for (auto *IInit : C->private_copies()) {
3020 Data.FirstprivateVars.push_back(*IRef);
3021 Data.FirstprivateCopies.push_back(IInit);
3022 Data.FirstprivateInits.push_back(*IElemInitRef);
3023 ++IRef;
3024 ++IElemInitRef;
3025 }
3026 }
3027 OMPPrivateScope TargetScope(*this);
3028 VarDecl *BPVD = nullptr;
3029 VarDecl *PVD = nullptr;
3030 VarDecl *SVD = nullptr;
3031 if (InputInfo.NumberOfTargetItems > 0) {
3032 auto *CD = CapturedDecl::Create(
3033 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3034 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3035 QualType BaseAndPointersType = getContext().getConstantArrayType(
3036 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3037 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003038 BPVD = createImplicitFirstprivateForType(
3039 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3040 PVD = createImplicitFirstprivateForType(
3041 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003042 QualType SizesType = getContext().getConstantArrayType(
3043 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3044 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003045 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3046 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003047 TargetScope.addPrivate(
3048 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3049 TargetScope.addPrivate(PVD,
3050 [&InputInfo]() { return InputInfo.PointersArray; });
3051 TargetScope.addPrivate(SVD,
3052 [&InputInfo]() { return InputInfo.SizesArray; });
3053 }
3054 (void)TargetScope.Privatize();
3055 // Build list of dependences.
3056 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3057 for (auto *IRef : C->varlists())
3058 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3059 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3060 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3061 // Set proper addresses for generated private copies.
3062 OMPPrivateScope Scope(CGF);
3063 if (!Data.FirstprivateVars.empty()) {
3064 enum { PrivatesParam = 2, CopyFnParam = 3 };
3065 auto *CopyFn = CGF.Builder.CreateLoad(
3066 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3067 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3068 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3069 // Map privates.
3070 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3071 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3072 CallArgs.push_back(PrivatesPtr);
3073 for (auto *E : Data.FirstprivateVars) {
3074 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3075 Address PrivatePtr =
3076 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3077 ".firstpriv.ptr.addr");
3078 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3079 CallArgs.push_back(PrivatePtr.getPointer());
3080 }
3081 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3082 CopyFn, CallArgs);
3083 for (auto &&Pair : PrivatePtrs) {
3084 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3085 CGF.getContext().getDeclAlign(Pair.first));
3086 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3087 }
3088 }
3089 // Privatize all private variables except for in_reduction items.
3090 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003091 if (InputInfo.NumberOfTargetItems > 0) {
3092 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3093 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3094 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3095 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3096 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3097 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3098 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003099
3100 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003101 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003102 BodyGen(CGF);
3103 };
3104 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3105 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3106 Data.NumberOfParts);
3107 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3108 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3109 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3110 SourceLocation());
3111
3112 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3113 SharedsTy, CapturedStruct, &IfCond, Data);
3114}
3115
Alexey Bataev7292c292016-04-25 12:22:29 +00003116void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3117 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003118 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003119 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003120 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003121 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003122 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3123 if (C->getNameModifier() == OMPD_unknown ||
3124 C->getNameModifier() == OMPD_task) {
3125 IfCond = C->getCondition();
3126 break;
3127 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003128 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003129
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003130 OMPTaskDataTy Data;
3131 // Check if we should emit tied or untied task.
3132 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003133 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3134 CGF.EmitStmt(CS->getCapturedStmt());
3135 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003136 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003137 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003138 const OMPTaskDataTy &Data) {
3139 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3140 SharedsTy, CapturedStruct, IfCond,
3141 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003142 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003143 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003144}
3145
Alexey Bataev9f797f32015-02-05 05:57:51 +00003146void CodeGenFunction::EmitOMPTaskyieldDirective(
3147 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003148 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003149}
3150
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003151void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003152 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003153}
3154
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003155void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3156 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003157}
3158
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003159void CodeGenFunction::EmitOMPTaskgroupDirective(
3160 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3162 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003163 if (const Expr *E = S.getReductionRef()) {
3164 SmallVector<const Expr *, 4> LHSs;
3165 SmallVector<const Expr *, 4> RHSs;
3166 OMPTaskDataTy Data;
3167 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3168 auto IPriv = C->privates().begin();
3169 auto IRed = C->reduction_ops().begin();
3170 auto ILHS = C->lhs_exprs().begin();
3171 auto IRHS = C->rhs_exprs().begin();
3172 for (const auto *Ref : C->varlists()) {
3173 Data.ReductionVars.emplace_back(Ref);
3174 Data.ReductionCopies.emplace_back(*IPriv);
3175 Data.ReductionOps.emplace_back(*IRed);
3176 LHSs.emplace_back(*ILHS);
3177 RHSs.emplace_back(*IRHS);
3178 std::advance(IPriv, 1);
3179 std::advance(IRed, 1);
3180 std::advance(ILHS, 1);
3181 std::advance(IRHS, 1);
3182 }
3183 }
3184 llvm::Value *ReductionDesc =
3185 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3186 LHSs, RHSs, Data);
3187 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3188 CGF.EmitVarDecl(*VD);
3189 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3190 /*Volatile=*/false, E->getType());
3191 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003192 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003193 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003194 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003195 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3196}
3197
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003198void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003199 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003200 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003201 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3202 FlushClause->varlist_end());
3203 }
3204 return llvm::None;
3205 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003206}
3207
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003208void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3209 const CodeGenLoopTy &CodeGenLoop,
3210 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003211 // Emit the loop iteration variable.
3212 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3213 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3214 EmitVarDecl(*IVDecl);
3215
3216 // Emit the iterations count variable.
3217 // If it is not a variable, Sema decided to calculate iterations count on each
3218 // iteration (e.g., it is foldable into a constant).
3219 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3220 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3221 // Emit calculation of the iterations count.
3222 EmitIgnoredExpr(S.getCalcLastIteration());
3223 }
3224
3225 auto &RT = CGM.getOpenMPRuntime();
3226
Carlo Bertolli962bb802017-01-03 18:24:42 +00003227 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003228 // Check pre-condition.
3229 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003230 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003231 // Skip the entire loop if we don't meet the precondition.
3232 // If the condition constant folds and can be elided, avoid emitting the
3233 // whole loop.
3234 bool CondConstant;
3235 llvm::BasicBlock *ContBlock = nullptr;
3236 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3237 if (!CondConstant)
3238 return;
3239 } else {
3240 auto *ThenBlock = createBasicBlock("omp.precond.then");
3241 ContBlock = createBasicBlock("omp.precond.end");
3242 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3243 getProfileCount(&S));
3244 EmitBlock(ThenBlock);
3245 incrementProfileCounter(&S);
3246 }
3247
Alexey Bataev617db5f2017-12-04 15:38:33 +00003248 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003249 // Emit 'then' code.
3250 {
3251 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003252
3253 LValue LB = EmitOMPHelperVar(
3254 *this, cast<DeclRefExpr>(
3255 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3256 ? S.getCombinedLowerBoundVariable()
3257 : S.getLowerBoundVariable())));
3258 LValue UB = EmitOMPHelperVar(
3259 *this, cast<DeclRefExpr>(
3260 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3261 ? S.getCombinedUpperBoundVariable()
3262 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003263 LValue ST =
3264 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3265 LValue IL =
3266 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3267
3268 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003269 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003270 // Emit implicit barrier to synchronize threads and avoid data races
3271 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003272 // lastprivate variables.
3273 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003274 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3275 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003276 }
3277 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003278 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003279 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3280 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003281 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003282 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003283 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003284 (void)LoopScope.Privatize();
3285
3286 // Detect the distribute schedule kind and chunk.
3287 llvm::Value *Chunk = nullptr;
3288 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3289 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3290 ScheduleKind = C->getDistScheduleKind();
3291 if (const auto *Ch = C->getChunkSize()) {
3292 Chunk = EmitScalarExpr(Ch);
3293 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003294 S.getIterationVariable()->getType(),
3295 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003296 }
3297 }
3298 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3299 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3300
3301 // OpenMP [2.10.8, distribute Construct, Description]
3302 // If dist_schedule is specified, kind must be static. If specified,
3303 // iterations are divided into chunks of size chunk_size, chunks are
3304 // assigned to the teams of the league in a round-robin fashion in the
3305 // order of the team number. When no chunk_size is specified, the
3306 // iteration space is divided into chunks that are approximately equal
3307 // in size, and at most one chunk is distributed to each team of the
3308 // league. The size of the chunks is unspecified in this case.
3309 if (RT.isStaticNonchunked(ScheduleKind,
3310 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003311 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3312 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003313 CGOpenMPRuntime::StaticRTInput StaticInit(
3314 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3315 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003316 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003317 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003318 auto LoopExit =
3319 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3320 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003321 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3322 ? S.getCombinedEnsureUpperBound()
3323 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003324 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003325 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3326 ? S.getCombinedInit()
3327 : S.getInit());
3328
3329 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3330 ? S.getCombinedCond()
3331 : S.getCond();
3332
3333 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003334 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003335 // when combined with 'for' (e.g. as in 'distribute parallel for')
3336 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3337 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3338 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3339 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003340 },
3341 [](CodeGenFunction &) {});
3342 EmitBlock(LoopExit.getBlock());
3343 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003344 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003345 } else {
3346 // Emit the outer loop, which requests its work chunk [LB..UB] from
3347 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003348 const OMPLoopArguments LoopArguments = {
3349 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3350 Chunk};
3351 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3352 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003353 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003354 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3355 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3356 return CGF.Builder.CreateIsNotNull(
3357 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3358 });
3359 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003360 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3361 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3362 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3363 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3364 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3365 isOpenMPSimdDirective(S.getDirectiveKind())) {
3366 ReductionKind = OMPD_parallel_for_simd;
3367 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3368 ReductionKind = OMPD_parallel_for;
3369 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3370 ReductionKind = OMPD_simd;
3371 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3372 S.hasClausesOfKind<OMPReductionClause>()) {
3373 llvm_unreachable(
3374 "No reduction clauses is allowed in distribute directive.");
3375 }
3376 EmitOMPReductionClauseFinal(S, ReductionKind);
3377 // Emit post-update of the reduction variables if IsLastIter != 0.
3378 emitPostUpdateForReductionClause(
3379 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3380 return CGF.Builder.CreateIsNotNull(
3381 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3382 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003383 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003384 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003385 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003386 EmitOMPLastprivateClauseFinal(
3387 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003388 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3389 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003390 }
3391
3392 // We're now done with the loop, so jump to the continuation block.
3393 if (ContBlock) {
3394 EmitBranch(ContBlock);
3395 EmitBlock(ContBlock, true);
3396 }
3397 }
3398}
3399
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003400void CodeGenFunction::EmitOMPDistributeDirective(
3401 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003402 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003403
3404 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003405 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003406 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003407 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003408}
3409
Alexey Bataev5f600d62015-09-29 03:48:57 +00003410static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3411 const CapturedStmt *S) {
3412 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3413 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3414 CGF.CapturedStmtInfo = &CapStmtInfo;
3415 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3416 Fn->addFnAttr(llvm::Attribute::NoInline);
3417 return Fn;
3418}
3419
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003420void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003421 if (S.hasClausesOfKind<OMPDependClause>()) {
3422 assert(!S.getAssociatedStmt() &&
3423 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003424 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3425 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003426 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003427 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003428 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003429 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3430 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003431 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003432 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003433 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3434 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3435 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003436 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3437 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003438 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003439 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003440 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003441 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003442 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003443 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003444 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003445}
3446
Alexey Bataevb57056f2015-01-22 06:17:56 +00003447static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003448 QualType SrcType, QualType DestType,
3449 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003450 assert(CGF.hasScalarEvaluationKind(DestType) &&
3451 "DestType must have scalar evaluation kind.");
3452 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3453 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003454 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3455 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003456 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003457 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003458}
3459
3460static CodeGenFunction::ComplexPairTy
3461convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003462 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003463 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3464 "DestType must have complex evaluation kind.");
3465 CodeGenFunction::ComplexPairTy ComplexVal;
3466 if (Val.isScalar()) {
3467 // Convert the input element to the element type of the complex.
3468 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003469 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3470 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003471 ComplexVal = CodeGenFunction::ComplexPairTy(
3472 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3473 } else {
3474 assert(Val.isComplex() && "Must be a scalar or complex.");
3475 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3476 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3477 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003478 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003479 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003480 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003481 }
3482 return ComplexVal;
3483}
3484
Alexey Bataev5e018f92015-04-23 06:35:10 +00003485static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3486 LValue LVal, RValue RVal) {
3487 if (LVal.isGlobalReg()) {
3488 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3489 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003490 CGF.EmitAtomicStore(RVal, LVal,
3491 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3492 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003493 LVal.isVolatile(), /*IsInit=*/false);
3494 }
3495}
3496
Alexey Bataev8524d152016-01-21 12:35:58 +00003497void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3498 QualType RValTy, SourceLocation Loc) {
3499 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003500 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003501 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3502 *this, RVal, RValTy, LVal.getType(), Loc)),
3503 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003504 break;
3505 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003506 EmitStoreOfComplex(
3507 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003508 /*isInit=*/false);
3509 break;
3510 case TEK_Aggregate:
3511 llvm_unreachable("Must be a scalar or complex.");
3512 }
3513}
3514
Alexey Bataevb57056f2015-01-22 06:17:56 +00003515static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3516 const Expr *X, const Expr *V,
3517 SourceLocation Loc) {
3518 // v = x;
3519 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3520 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3521 LValue XLValue = CGF.EmitLValue(X);
3522 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003523 RValue Res = XLValue.isGlobalReg()
3524 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003525 : CGF.EmitAtomicLoad(
3526 XLValue, Loc,
3527 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3528 : llvm::AtomicOrdering::Monotonic,
3529 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003530 // OpenMP, 2.12.6, atomic Construct
3531 // Any atomic construct with a seq_cst clause forces the atomically
3532 // performed operation to include an implicit flush operation without a
3533 // list.
3534 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003535 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003536 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003537}
3538
Alexey Bataevb8329262015-02-27 06:33:30 +00003539static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3540 const Expr *X, const Expr *E,
3541 SourceLocation Loc) {
3542 // x = expr;
3543 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003544 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003545 // OpenMP, 2.12.6, atomic Construct
3546 // Any atomic construct with a seq_cst clause forces the atomically
3547 // performed operation to include an implicit flush operation without a
3548 // list.
3549 if (IsSeqCst)
3550 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3551}
3552
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003553static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3554 RValue Update,
3555 BinaryOperatorKind BO,
3556 llvm::AtomicOrdering AO,
3557 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003558 auto &Context = CGF.CGM.getContext();
3559 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003560 // expression is simple and atomic is allowed for the given type for the
3561 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003562 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003563 !Update.getScalarVal()->getType()->isIntegerTy() ||
3564 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3565 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003566 X.getAddress().getElementType())) ||
3567 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003568 !Context.getTargetInfo().hasBuiltinAtomic(
3569 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003570 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003571
3572 llvm::AtomicRMWInst::BinOp RMWOp;
3573 switch (BO) {
3574 case BO_Add:
3575 RMWOp = llvm::AtomicRMWInst::Add;
3576 break;
3577 case BO_Sub:
3578 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003579 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003580 RMWOp = llvm::AtomicRMWInst::Sub;
3581 break;
3582 case BO_And:
3583 RMWOp = llvm::AtomicRMWInst::And;
3584 break;
3585 case BO_Or:
3586 RMWOp = llvm::AtomicRMWInst::Or;
3587 break;
3588 case BO_Xor:
3589 RMWOp = llvm::AtomicRMWInst::Xor;
3590 break;
3591 case BO_LT:
3592 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3593 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3594 : llvm::AtomicRMWInst::Max)
3595 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3596 : llvm::AtomicRMWInst::UMax);
3597 break;
3598 case BO_GT:
3599 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3600 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3601 : llvm::AtomicRMWInst::Min)
3602 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3603 : llvm::AtomicRMWInst::UMin);
3604 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003605 case BO_Assign:
3606 RMWOp = llvm::AtomicRMWInst::Xchg;
3607 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003608 case BO_Mul:
3609 case BO_Div:
3610 case BO_Rem:
3611 case BO_Shl:
3612 case BO_Shr:
3613 case BO_LAnd:
3614 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003615 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003616 case BO_PtrMemD:
3617 case BO_PtrMemI:
3618 case BO_LE:
3619 case BO_GE:
3620 case BO_EQ:
3621 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003622 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003623 case BO_AddAssign:
3624 case BO_SubAssign:
3625 case BO_AndAssign:
3626 case BO_OrAssign:
3627 case BO_XorAssign:
3628 case BO_MulAssign:
3629 case BO_DivAssign:
3630 case BO_RemAssign:
3631 case BO_ShlAssign:
3632 case BO_ShrAssign:
3633 case BO_Comma:
3634 llvm_unreachable("Unsupported atomic update operation");
3635 }
3636 auto *UpdateVal = Update.getScalarVal();
3637 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3638 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003639 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003640 X.getType()->hasSignedIntegerRepresentation());
3641 }
John McCall7f416cc2015-09-08 08:05:57 +00003642 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003643 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003644}
3645
Alexey Bataev5e018f92015-04-23 06:35:10 +00003646std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003647 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3648 llvm::AtomicOrdering AO, SourceLocation Loc,
3649 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3650 // Update expressions are allowed to have the following forms:
3651 // x binop= expr; -> xrval + expr;
3652 // x++, ++x -> xrval + 1;
3653 // x--, --x -> xrval - 1;
3654 // x = x binop expr; -> xrval binop expr
3655 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003656 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3657 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003658 if (X.isGlobalReg()) {
3659 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3660 // 'xrval'.
3661 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3662 } else {
3663 // Perform compare-and-swap procedure.
3664 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003665 }
3666 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003667 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003668}
3669
3670static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3671 const Expr *X, const Expr *E,
3672 const Expr *UE, bool IsXLHSInRHSPart,
3673 SourceLocation Loc) {
3674 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3675 "Update expr in 'atomic update' must be a binary operator.");
3676 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3677 // Update expressions are allowed to have the following forms:
3678 // x binop= expr; -> xrval + expr;
3679 // x++, ++x -> xrval + 1;
3680 // x--, --x -> xrval - 1;
3681 // x = x binop expr; -> xrval binop expr
3682 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003683 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003684 LValue XLValue = CGF.EmitLValue(X);
3685 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003686 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3687 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003688 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3689 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3690 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3691 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3692 auto Gen =
3693 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3694 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3695 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3696 return CGF.EmitAnyExpr(UE);
3697 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003698 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3699 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3700 // OpenMP, 2.12.6, atomic Construct
3701 // Any atomic construct with a seq_cst clause forces the atomically
3702 // performed operation to include an implicit flush operation without a
3703 // list.
3704 if (IsSeqCst)
3705 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3706}
3707
3708static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003709 QualType SourceType, QualType ResType,
3710 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003711 switch (CGF.getEvaluationKind(ResType)) {
3712 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003713 return RValue::get(
3714 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003715 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003716 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003717 return RValue::getComplex(Res.first, Res.second);
3718 }
3719 case TEK_Aggregate:
3720 break;
3721 }
3722 llvm_unreachable("Must be a scalar or complex.");
3723}
3724
3725static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3726 bool IsPostfixUpdate, const Expr *V,
3727 const Expr *X, const Expr *E,
3728 const Expr *UE, bool IsXLHSInRHSPart,
3729 SourceLocation Loc) {
3730 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3731 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3732 RValue NewVVal;
3733 LValue VLValue = CGF.EmitLValue(V);
3734 LValue XLValue = CGF.EmitLValue(X);
3735 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003736 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3737 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003738 QualType NewVValType;
3739 if (UE) {
3740 // 'x' is updated with some additional value.
3741 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3742 "Update expr in 'atomic capture' must be a binary operator.");
3743 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3744 // Update expressions are allowed to have the following forms:
3745 // x binop= expr; -> xrval + expr;
3746 // x++, ++x -> xrval + 1;
3747 // x--, --x -> xrval - 1;
3748 // x = x binop expr; -> xrval binop expr
3749 // x = expr Op x; - > expr binop xrval;
3750 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3751 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3752 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3753 NewVValType = XRValExpr->getType();
3754 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3755 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003756 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003757 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3758 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3759 RValue Res = CGF.EmitAnyExpr(UE);
3760 NewVVal = IsPostfixUpdate ? XRValue : Res;
3761 return Res;
3762 };
3763 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3764 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3765 if (Res.first) {
3766 // 'atomicrmw' instruction was generated.
3767 if (IsPostfixUpdate) {
3768 // Use old value from 'atomicrmw'.
3769 NewVVal = Res.second;
3770 } else {
3771 // 'atomicrmw' does not provide new value, so evaluate it using old
3772 // value of 'x'.
3773 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3774 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3775 NewVVal = CGF.EmitAnyExpr(UE);
3776 }
3777 }
3778 } else {
3779 // 'x' is simply rewritten with some 'expr'.
3780 NewVValType = X->getType().getNonReferenceType();
3781 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003782 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003783 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003784 NewVVal = XRValue;
3785 return ExprRValue;
3786 };
3787 // Try to perform atomicrmw xchg, otherwise simple exchange.
3788 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3789 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3790 Loc, Gen);
3791 if (Res.first) {
3792 // 'atomicrmw' instruction was generated.
3793 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3794 }
3795 }
3796 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003797 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003798 // OpenMP, 2.12.6, atomic Construct
3799 // Any atomic construct with a seq_cst clause forces the atomically
3800 // performed operation to include an implicit flush operation without a
3801 // list.
3802 if (IsSeqCst)
3803 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3804}
3805
Alexey Bataevb57056f2015-01-22 06:17:56 +00003806static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003807 bool IsSeqCst, bool IsPostfixUpdate,
3808 const Expr *X, const Expr *V, const Expr *E,
3809 const Expr *UE, bool IsXLHSInRHSPart,
3810 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003811 switch (Kind) {
3812 case OMPC_read:
3813 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3814 break;
3815 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003816 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3817 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003818 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003819 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003820 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3821 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003822 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003823 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3824 IsXLHSInRHSPart, Loc);
3825 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003826 case OMPC_if:
3827 case OMPC_final:
3828 case OMPC_num_threads:
3829 case OMPC_private:
3830 case OMPC_firstprivate:
3831 case OMPC_lastprivate:
3832 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003833 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003834 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003835 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003836 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003837 case OMPC_collapse:
3838 case OMPC_default:
3839 case OMPC_seq_cst:
3840 case OMPC_shared:
3841 case OMPC_linear:
3842 case OMPC_aligned:
3843 case OMPC_copyin:
3844 case OMPC_copyprivate:
3845 case OMPC_flush:
3846 case OMPC_proc_bind:
3847 case OMPC_schedule:
3848 case OMPC_ordered:
3849 case OMPC_nowait:
3850 case OMPC_untied:
3851 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003852 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003853 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003854 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003855 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003856 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003857 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003858 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003859 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003860 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003861 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003862 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003863 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003864 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003865 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003866 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003867 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003868 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003869 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003870 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003871 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003872 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3873 }
3874}
3875
3876void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003877 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003878 OpenMPClauseKind Kind = OMPC_unknown;
3879 for (auto *C : S.clauses()) {
3880 // Find first clause (skip seq_cst clause, if it is first).
3881 if (C->getClauseKind() != OMPC_seq_cst) {
3882 Kind = C->getClauseKind();
3883 break;
3884 }
3885 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003886
Alexey Bataev475a7442018-01-12 19:39:11 +00003887 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003888 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003889 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003890 }
3891 // Processing for statements under 'atomic capture'.
3892 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3893 for (const auto *C : Compound->body()) {
3894 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3895 enterFullExpression(EWC);
3896 }
3897 }
3898 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003899
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003900 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3901 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003902 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003903 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3904 S.getV(), S.getExpr(), S.getUpdateExpr(),
3905 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003906 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003907 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003908 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003909}
3910
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003911static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3912 const OMPExecutableDirective &S,
3913 const RegionCodeGenTy &CodeGen) {
3914 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3915 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003916
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003917 // On device emit this construct as inlined code.
3918 if (CGM.getLangOpts().OpenMPIsDevice) {
3919 OMPLexicalScope Scope(CGF, S, OMPD_target);
3920 CGM.getOpenMPRuntime().emitInlinedDirective(
3921 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3922 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
3923 });
3924 return;
3925 }
3926
Samuel Antaoee8fb302016-01-06 13:42:12 +00003927 llvm::Function *Fn = nullptr;
3928 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003929
Samuel Antaobed3c462015-10-02 16:14:20 +00003930 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003931 // Check for the at most one if clause associated with the target region.
3932 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3933 if (C->getNameModifier() == OMPD_unknown ||
3934 C->getNameModifier() == OMPD_target) {
3935 IfCond = C->getCondition();
3936 break;
3937 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003938 }
3939
3940 // Check if we have any device clause associated with the directive.
3941 const Expr *Device = nullptr;
3942 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3943 Device = C->getDevice();
3944 }
3945
Samuel Antaoee8fb302016-01-06 13:42:12 +00003946 // Check if we have an if clause whose conditional always evaluates to false
3947 // or if we do not have any targets specified. If so the target region is not
3948 // an offload entry point.
3949 bool IsOffloadEntry = true;
3950 if (IfCond) {
3951 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003952 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003953 IsOffloadEntry = false;
3954 }
3955 if (CGM.getLangOpts().OMPTargetTriples.empty())
3956 IsOffloadEntry = false;
3957
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003958 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003959 StringRef ParentName;
3960 // In case we have Ctors/Dtors we use the complete type variant to produce
3961 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003962 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003963 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003964 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003965 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3966 else
3967 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003968 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003969
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003970 // Emit target region as a standalone region.
3971 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3972 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003973 OMPLexicalScope Scope(CGF, S, OMPD_task);
3974 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003975}
3976
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003977static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3978 PrePostActionTy &Action) {
3979 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3980 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3981 CGF.EmitOMPPrivateClause(S, PrivateScope);
3982 (void)PrivateScope.Privatize();
3983
3984 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003985 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003986}
3987
3988void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3989 StringRef ParentName,
3990 const OMPTargetDirective &S) {
3991 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3992 emitTargetRegion(CGF, S, Action);
3993 };
3994 llvm::Function *Fn;
3995 llvm::Constant *Addr;
3996 // Emit target region as a standalone region.
3997 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3998 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3999 assert(Fn && Addr && "Target device function emission failed.");
4000}
4001
4002void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4003 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4004 emitTargetRegion(CGF, S, Action);
4005 };
4006 emitCommonOMPTargetDirective(*this, S, CodeGen);
4007}
4008
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004009static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4010 const OMPExecutableDirective &S,
4011 OpenMPDirectiveKind InnermostKind,
4012 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004013 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4014 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4015 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004016
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004017 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4018 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004019 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004020 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4021 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004022
Carlo Bertollic6872252016-04-04 15:55:02 +00004023 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4024 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004025 }
4026
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004027 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004028 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4029 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004030 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4031 CapturedVars);
4032}
4033
4034void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004035 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004036 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004037 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004038 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4039 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004040 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004041 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004042 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004043 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004044 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004045 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004046 emitPostUpdateForReductionClause(
4047 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004048}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004049
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004050static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4051 const OMPTargetTeamsDirective &S) {
4052 auto *CS = S.getCapturedStmt(OMPD_teams);
4053 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004054 // Emit teams region as a standalone region.
4055 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4056 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4057 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4058 CGF.EmitOMPPrivateClause(S, PrivateScope);
4059 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4060 (void)PrivateScope.Privatize();
4061 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004062 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004063 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004064 };
4065 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004066 emitPostUpdateForReductionClause(
4067 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004068}
4069
4070void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4071 CodeGenModule &CGM, StringRef ParentName,
4072 const OMPTargetTeamsDirective &S) {
4073 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4074 emitTargetTeamsRegion(CGF, Action, S);
4075 };
4076 llvm::Function *Fn;
4077 llvm::Constant *Addr;
4078 // Emit target region as a standalone region.
4079 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4080 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4081 assert(Fn && Addr && "Target device function emission failed.");
4082}
4083
4084void CodeGenFunction::EmitOMPTargetTeamsDirective(
4085 const OMPTargetTeamsDirective &S) {
4086 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4087 emitTargetTeamsRegion(CGF, Action, S);
4088 };
4089 emitCommonOMPTargetDirective(*this, S, CodeGen);
4090}
4091
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004092static void
4093emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4094 const OMPTargetTeamsDistributeDirective &S) {
4095 Action.Enter(CGF);
4096 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4097 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4098 };
4099
4100 // Emit teams region as a standalone region.
4101 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4102 PrePostActionTy &) {
4103 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4104 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4105 (void)PrivateScope.Privatize();
4106 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4107 CodeGenDistribute);
4108 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4109 };
4110 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4111 emitPostUpdateForReductionClause(CGF, S,
4112 [](CodeGenFunction &) { return nullptr; });
4113}
4114
4115void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4116 CodeGenModule &CGM, StringRef ParentName,
4117 const OMPTargetTeamsDistributeDirective &S) {
4118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4119 emitTargetTeamsDistributeRegion(CGF, Action, S);
4120 };
4121 llvm::Function *Fn;
4122 llvm::Constant *Addr;
4123 // Emit target region as a standalone region.
4124 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4125 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4126 assert(Fn && Addr && "Target device function emission failed.");
4127}
4128
4129void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4130 const OMPTargetTeamsDistributeDirective &S) {
4131 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4132 emitTargetTeamsDistributeRegion(CGF, Action, S);
4133 };
4134 emitCommonOMPTargetDirective(*this, S, CodeGen);
4135}
4136
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004137static void emitTargetTeamsDistributeSimdRegion(
4138 CodeGenFunction &CGF, PrePostActionTy &Action,
4139 const OMPTargetTeamsDistributeSimdDirective &S) {
4140 Action.Enter(CGF);
4141 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4142 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4143 };
4144
4145 // Emit teams region as a standalone region.
4146 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4147 PrePostActionTy &) {
4148 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4149 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4150 (void)PrivateScope.Privatize();
4151 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4152 CodeGenDistribute);
4153 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4154 };
4155 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4156 emitPostUpdateForReductionClause(CGF, S,
4157 [](CodeGenFunction &) { return nullptr; });
4158}
4159
4160void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4161 CodeGenModule &CGM, StringRef ParentName,
4162 const OMPTargetTeamsDistributeSimdDirective &S) {
4163 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4164 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4165 };
4166 llvm::Function *Fn;
4167 llvm::Constant *Addr;
4168 // Emit target region as a standalone region.
4169 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4170 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4171 assert(Fn && Addr && "Target device function emission failed.");
4172}
4173
4174void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4175 const OMPTargetTeamsDistributeSimdDirective &S) {
4176 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4177 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4178 };
4179 emitCommonOMPTargetDirective(*this, S, CodeGen);
4180}
4181
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004182void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4183 const OMPTeamsDistributeDirective &S) {
4184
4185 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4186 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4187 };
4188
4189 // Emit teams region as a standalone region.
4190 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4191 PrePostActionTy &) {
4192 OMPPrivateScope PrivateScope(CGF);
4193 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4194 (void)PrivateScope.Privatize();
4195 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4196 CodeGenDistribute);
4197 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4198 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004199 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004200 emitPostUpdateForReductionClause(*this, S,
4201 [](CodeGenFunction &) { return nullptr; });
4202}
4203
Alexey Bataev999277a2017-12-06 14:31:09 +00004204void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4205 const OMPTeamsDistributeSimdDirective &S) {
4206 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4207 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4208 };
4209
4210 // Emit teams region as a standalone region.
4211 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4212 PrePostActionTy &) {
4213 OMPPrivateScope PrivateScope(CGF);
4214 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4215 (void)PrivateScope.Privatize();
4216 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4217 CodeGenDistribute);
4218 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4219 };
4220 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4221 emitPostUpdateForReductionClause(*this, S,
4222 [](CodeGenFunction &) { return nullptr; });
4223}
4224
Carlo Bertolli62fae152017-11-20 20:46:39 +00004225void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4226 const OMPTeamsDistributeParallelForDirective &S) {
4227 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4228 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4229 S.getDistInc());
4230 };
4231
4232 // Emit teams region as a standalone region.
4233 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4234 PrePostActionTy &) {
4235 OMPPrivateScope PrivateScope(CGF);
4236 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4237 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004238 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4239 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004240 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4241 };
4242 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4243 emitPostUpdateForReductionClause(*this, S,
4244 [](CodeGenFunction &) { return nullptr; });
4245}
4246
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004247void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4248 const OMPTeamsDistributeParallelForSimdDirective &S) {
4249 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4250 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4251 S.getDistInc());
4252 };
4253
4254 // Emit teams region as a standalone region.
4255 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4256 PrePostActionTy &) {
4257 OMPPrivateScope PrivateScope(CGF);
4258 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4259 (void)PrivateScope.Privatize();
4260 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4261 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4262 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4263 };
4264 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4265 emitPostUpdateForReductionClause(*this, S,
4266 [](CodeGenFunction &) { return nullptr; });
4267}
4268
Carlo Bertolli52978c32018-01-03 21:12:44 +00004269static void emitTargetTeamsDistributeParallelForRegion(
4270 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4271 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004272 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004273 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4274 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4275 S.getDistInc());
4276 };
4277
4278 // Emit teams region as a standalone region.
4279 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4280 PrePostActionTy &) {
4281 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4282 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4283 (void)PrivateScope.Privatize();
4284 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4285 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4286 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4287 };
4288
4289 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4290 CodeGenTeams);
4291 emitPostUpdateForReductionClause(CGF, S,
4292 [](CodeGenFunction &) { return nullptr; });
4293}
4294
4295void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4296 CodeGenModule &CGM, StringRef ParentName,
4297 const OMPTargetTeamsDistributeParallelForDirective &S) {
4298 // Emit SPMD target teams distribute parallel for region as a standalone
4299 // region.
4300 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4301 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4302 };
4303 llvm::Function *Fn;
4304 llvm::Constant *Addr;
4305 // Emit target region as a standalone region.
4306 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4307 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4308 assert(Fn && Addr && "Target device function emission failed.");
4309}
4310
4311void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4312 const OMPTargetTeamsDistributeParallelForDirective &S) {
4313 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4314 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4315 };
4316 emitCommonOMPTargetDirective(*this, S, CodeGen);
4317}
4318
Alexey Bataev647dd842018-01-15 20:59:40 +00004319static void emitTargetTeamsDistributeParallelForSimdRegion(
4320 CodeGenFunction &CGF,
4321 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4322 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004323 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004324 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4325 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4326 S.getDistInc());
4327 };
4328
4329 // Emit teams region as a standalone region.
4330 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4331 PrePostActionTy &) {
4332 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4333 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4334 (void)PrivateScope.Privatize();
4335 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4336 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4337 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4338 };
4339
4340 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4341 CodeGenTeams);
4342 emitPostUpdateForReductionClause(CGF, S,
4343 [](CodeGenFunction &) { return nullptr; });
4344}
4345
4346void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4347 CodeGenModule &CGM, StringRef ParentName,
4348 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4349 // Emit SPMD target teams distribute parallel for simd region as a standalone
4350 // region.
4351 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4352 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4353 };
4354 llvm::Function *Fn;
4355 llvm::Constant *Addr;
4356 // Emit target region as a standalone region.
4357 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4358 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4359 assert(Fn && Addr && "Target device function emission failed.");
4360}
4361
4362void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4363 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4364 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4365 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4366 };
4367 emitCommonOMPTargetDirective(*this, S, CodeGen);
4368}
4369
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004370void CodeGenFunction::EmitOMPCancellationPointDirective(
4371 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004372 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4373 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004374}
4375
Alexey Bataev80909872015-07-02 11:25:17 +00004376void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004377 const Expr *IfCond = nullptr;
4378 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4379 if (C->getNameModifier() == OMPD_unknown ||
4380 C->getNameModifier() == OMPD_cancel) {
4381 IfCond = C->getCondition();
4382 break;
4383 }
4384 }
4385 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004386 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004387}
4388
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004389CodeGenFunction::JumpDest
4390CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004391 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4392 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004393 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004394 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004395 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4396 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004397 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004398 Kind == OMPD_teams_distribute_parallel_for ||
4399 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004400 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004401}
Michael Wong65f367f2015-07-21 13:44:28 +00004402
Samuel Antaocc10b852016-07-28 14:23:26 +00004403void CodeGenFunction::EmitOMPUseDevicePtrClause(
4404 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4405 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4406 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4407 auto OrigVarIt = C.varlist_begin();
4408 auto InitIt = C.inits().begin();
4409 for (auto PvtVarIt : C.private_copies()) {
4410 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4411 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4412 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4413
4414 // In order to identify the right initializer we need to match the
4415 // declaration used by the mapping logic. In some cases we may get
4416 // OMPCapturedExprDecl that refers to the original declaration.
4417 const ValueDecl *MatchingVD = OrigVD;
4418 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4419 // OMPCapturedExprDecl are used to privative fields of the current
4420 // structure.
4421 auto *ME = cast<MemberExpr>(OED->getInit());
4422 assert(isa<CXXThisExpr>(ME->getBase()) &&
4423 "Base should be the current struct!");
4424 MatchingVD = ME->getMemberDecl();
4425 }
4426
4427 // If we don't have information about the current list item, move on to
4428 // the next one.
4429 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4430 if (InitAddrIt == CaptureDeviceAddrMap.end())
4431 continue;
4432
4433 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4434 // Initialize the temporary initialization variable with the address we
4435 // get from the runtime library. We have to cast the source address
4436 // because it is always a void *. References are materialized in the
4437 // privatization scope, so the initialization here disregards the fact
4438 // the original variable is a reference.
4439 QualType AddrQTy =
4440 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4441 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4442 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4443 setAddrOfLocalVar(InitVD, InitAddr);
4444
4445 // Emit private declaration, it will be initialized by the value we
4446 // declaration we just added to the local declarations map.
4447 EmitDecl(*PvtVD);
4448
4449 // The initialization variables reached its purpose in the emission
4450 // ofthe previous declaration, so we don't need it anymore.
4451 LocalDeclMap.erase(InitVD);
4452
4453 // Return the address of the private variable.
4454 return GetAddrOfLocalVar(PvtVD);
4455 });
4456 assert(IsRegistered && "firstprivate var already registered as private");
4457 // Silence the warning about unused variable.
4458 (void)IsRegistered;
4459
4460 ++OrigVarIt;
4461 ++InitIt;
4462 }
4463}
4464
Michael Wong65f367f2015-07-21 13:44:28 +00004465// Generate the instructions for '#pragma omp target data' directive.
4466void CodeGenFunction::EmitOMPTargetDataDirective(
4467 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004468 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4469
4470 // Create a pre/post action to signal the privatization of the device pointer.
4471 // This action can be replaced by the OpenMP runtime code generation to
4472 // deactivate privatization.
4473 bool PrivatizeDevicePointers = false;
4474 class DevicePointerPrivActionTy : public PrePostActionTy {
4475 bool &PrivatizeDevicePointers;
4476
4477 public:
4478 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4479 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4480 void Enter(CodeGenFunction &CGF) override {
4481 PrivatizeDevicePointers = true;
4482 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004483 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004484 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4485
4486 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004487 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004488 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004489 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004490 };
4491
4492 // Codegen that selects wheather to generate the privatization code or not.
4493 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4494 &InnermostCodeGen](CodeGenFunction &CGF,
4495 PrePostActionTy &Action) {
4496 RegionCodeGenTy RCG(InnermostCodeGen);
4497 PrivatizeDevicePointers = false;
4498
4499 // Call the pre-action to change the status of PrivatizeDevicePointers if
4500 // needed.
4501 Action.Enter(CGF);
4502
4503 if (PrivatizeDevicePointers) {
4504 OMPPrivateScope PrivateScope(CGF);
4505 // Emit all instances of the use_device_ptr clause.
4506 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4507 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4508 Info.CaptureDeviceAddrMap);
4509 (void)PrivateScope.Privatize();
4510 RCG(CGF);
4511 } else
4512 RCG(CGF);
4513 };
4514
4515 // Forward the provided action to the privatization codegen.
4516 RegionCodeGenTy PrivRCG(PrivCodeGen);
4517 PrivRCG.setAction(Action);
4518
4519 // Notwithstanding the body of the region is emitted as inlined directive,
4520 // we don't use an inline scope as changes in the references inside the
4521 // region are expected to be visible outside, so we do not privative them.
4522 OMPLexicalScope Scope(CGF, S);
4523 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4524 PrivRCG);
4525 };
4526
4527 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004528
4529 // If we don't have target devices, don't bother emitting the data mapping
4530 // code.
4531 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004532 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004533 return;
4534 }
4535
4536 // Check if we have any if clause associated with the directive.
4537 const Expr *IfCond = nullptr;
4538 if (auto *C = S.getSingleClause<OMPIfClause>())
4539 IfCond = C->getCondition();
4540
4541 // Check if we have any device clause associated with the directive.
4542 const Expr *Device = nullptr;
4543 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4544 Device = C->getDevice();
4545
Samuel Antaocc10b852016-07-28 14:23:26 +00004546 // Set the action to signal privatization of device pointers.
4547 RCG.setAction(PrivAction);
4548
4549 // Emit region code.
4550 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4551 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004552}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004553
Samuel Antaodf67fc42016-01-19 19:15:56 +00004554void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4555 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004556 // If we don't have target devices, don't bother emitting the data mapping
4557 // code.
4558 if (CGM.getLangOpts().OMPTargetTriples.empty())
4559 return;
4560
4561 // Check if we have any if clause associated with the directive.
4562 const Expr *IfCond = nullptr;
4563 if (auto *C = S.getSingleClause<OMPIfClause>())
4564 IfCond = C->getCondition();
4565
4566 // Check if we have any device clause associated with the directive.
4567 const Expr *Device = nullptr;
4568 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4569 Device = C->getDevice();
4570
Alexey Bataev475a7442018-01-12 19:39:11 +00004571 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004572 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004573}
4574
Samuel Antao72590762016-01-19 20:04:50 +00004575void CodeGenFunction::EmitOMPTargetExitDataDirective(
4576 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004577 // If we don't have target devices, don't bother emitting the data mapping
4578 // code.
4579 if (CGM.getLangOpts().OMPTargetTriples.empty())
4580 return;
4581
4582 // Check if we have any if clause associated with the directive.
4583 const Expr *IfCond = nullptr;
4584 if (auto *C = S.getSingleClause<OMPIfClause>())
4585 IfCond = C->getCondition();
4586
4587 // Check if we have any device clause associated with the directive.
4588 const Expr *Device = nullptr;
4589 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4590 Device = C->getDevice();
4591
Alexey Bataev475a7442018-01-12 19:39:11 +00004592 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004593 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004594}
4595
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004596static void emitTargetParallelRegion(CodeGenFunction &CGF,
4597 const OMPTargetParallelDirective &S,
4598 PrePostActionTy &Action) {
4599 // Get the captured statement associated with the 'parallel' region.
4600 auto *CS = S.getCapturedStmt(OMPD_parallel);
4601 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004602 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4603 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4604 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4605 CGF.EmitOMPPrivateClause(S, PrivateScope);
4606 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4607 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004608 // TODO: Add support for clauses.
4609 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004610 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004611 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004612 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4613 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004614 emitPostUpdateForReductionClause(
4615 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004616}
4617
4618void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4619 CodeGenModule &CGM, StringRef ParentName,
4620 const OMPTargetParallelDirective &S) {
4621 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4622 emitTargetParallelRegion(CGF, S, Action);
4623 };
4624 llvm::Function *Fn;
4625 llvm::Constant *Addr;
4626 // Emit target region as a standalone region.
4627 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4628 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4629 assert(Fn && Addr && "Target device function emission failed.");
4630}
4631
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004632void CodeGenFunction::EmitOMPTargetParallelDirective(
4633 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004634 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4635 emitTargetParallelRegion(CGF, S, Action);
4636 };
4637 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004638}
4639
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004640static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4641 const OMPTargetParallelForDirective &S,
4642 PrePostActionTy &Action) {
4643 Action.Enter(CGF);
4644 // Emit directive as a combined directive that consists of two implicit
4645 // directives: 'parallel' with 'for' directive.
4646 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004647 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4648 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004649 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4650 emitDispatchForLoopBounds);
4651 };
4652 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4653 emitEmptyBoundParameters);
4654}
4655
4656void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4657 CodeGenModule &CGM, StringRef ParentName,
4658 const OMPTargetParallelForDirective &S) {
4659 // Emit SPMD target parallel for region as a standalone region.
4660 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4661 emitTargetParallelForRegion(CGF, S, Action);
4662 };
4663 llvm::Function *Fn;
4664 llvm::Constant *Addr;
4665 // Emit target region as a standalone region.
4666 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4667 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4668 assert(Fn && Addr && "Target device function emission failed.");
4669}
4670
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004671void CodeGenFunction::EmitOMPTargetParallelForDirective(
4672 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004673 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4674 emitTargetParallelForRegion(CGF, S, Action);
4675 };
4676 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004677}
4678
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004679static void
4680emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4681 const OMPTargetParallelForSimdDirective &S,
4682 PrePostActionTy &Action) {
4683 Action.Enter(CGF);
4684 // Emit directive as a combined directive that consists of two implicit
4685 // directives: 'parallel' with 'for' directive.
4686 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4687 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4688 emitDispatchForLoopBounds);
4689 };
4690 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4691 emitEmptyBoundParameters);
4692}
4693
4694void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4695 CodeGenModule &CGM, StringRef ParentName,
4696 const OMPTargetParallelForSimdDirective &S) {
4697 // Emit SPMD target parallel for region as a standalone region.
4698 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4699 emitTargetParallelForSimdRegion(CGF, S, Action);
4700 };
4701 llvm::Function *Fn;
4702 llvm::Constant *Addr;
4703 // Emit target region as a standalone region.
4704 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4705 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4706 assert(Fn && Addr && "Target device function emission failed.");
4707}
4708
4709void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4710 const OMPTargetParallelForSimdDirective &S) {
4711 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4712 emitTargetParallelForSimdRegion(CGF, S, Action);
4713 };
4714 emitCommonOMPTargetDirective(*this, S, CodeGen);
4715}
4716
Alexey Bataev7292c292016-04-25 12:22:29 +00004717/// Emit a helper variable and return corresponding lvalue.
4718static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4719 const ImplicitParamDecl *PVD,
4720 CodeGenFunction::OMPPrivateScope &Privates) {
4721 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4722 Privates.addPrivate(
4723 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4724}
4725
4726void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4727 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4728 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004729 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004730 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4731 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4732 const Expr *IfCond = nullptr;
4733 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4734 if (C->getNameModifier() == OMPD_unknown ||
4735 C->getNameModifier() == OMPD_taskloop) {
4736 IfCond = C->getCondition();
4737 break;
4738 }
4739 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004740
4741 OMPTaskDataTy Data;
4742 // Check if taskloop must be emitted without taskgroup.
4743 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004744 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004745 Data.Tied = true;
4746 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004747 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4748 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004749 Data.Schedule.setInt(/*IntVal=*/false);
4750 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004751 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4752 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004753 Data.Schedule.setInt(/*IntVal=*/true);
4754 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004755 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004756
4757 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4758 // if (PreCond) {
4759 // for (IV in 0..LastIteration) BODY;
4760 // <Final counter/linear vars updates>;
4761 // }
4762 //
4763
4764 // Emit: if (PreCond) - begin.
4765 // If the condition constant folds and can be elided, avoid emitting the
4766 // whole loop.
4767 bool CondConstant;
4768 llvm::BasicBlock *ContBlock = nullptr;
4769 OMPLoopScope PreInitScope(CGF, S);
4770 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4771 if (!CondConstant)
4772 return;
4773 } else {
4774 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4775 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4776 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4777 CGF.getProfileCount(&S));
4778 CGF.EmitBlock(ThenBlock);
4779 CGF.incrementProfileCounter(&S);
4780 }
4781
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004782 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4783 CGF.EmitOMPSimdInit(S);
4784
Alexey Bataev7292c292016-04-25 12:22:29 +00004785 OMPPrivateScope LoopScope(CGF);
4786 // Emit helper vars inits.
4787 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4788 auto *I = CS->getCapturedDecl()->param_begin();
4789 auto *LBP = std::next(I, LowerBound);
4790 auto *UBP = std::next(I, UpperBound);
4791 auto *STP = std::next(I, Stride);
4792 auto *LIP = std::next(I, LastIter);
4793 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4794 LoopScope);
4795 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4796 LoopScope);
4797 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4798 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4799 LoopScope);
4800 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004801 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004802 (void)LoopScope.Privatize();
4803 // Emit the loop iteration variable.
4804 const Expr *IVExpr = S.getIterationVariable();
4805 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4806 CGF.EmitVarDecl(*IVDecl);
4807 CGF.EmitIgnoredExpr(S.getInit());
4808
4809 // Emit the iterations count variable.
4810 // If it is not a variable, Sema decided to calculate iterations count on
4811 // each iteration (e.g., it is foldable into a constant).
4812 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4813 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4814 // Emit calculation of the iterations count.
4815 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4816 }
4817
4818 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4819 S.getInc(),
4820 [&S](CodeGenFunction &CGF) {
4821 CGF.EmitOMPLoopBody(S, JumpDest());
4822 CGF.EmitStopPoint(&S);
4823 },
4824 [](CodeGenFunction &) {});
4825 // Emit: if (PreCond) - end.
4826 if (ContBlock) {
4827 CGF.EmitBranch(ContBlock);
4828 CGF.EmitBlock(ContBlock, true);
4829 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004830 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4831 if (HasLastprivateClause) {
4832 CGF.EmitOMPLastprivateClauseFinal(
4833 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4834 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4835 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4836 (*LIP)->getType(), S.getLocStart())));
4837 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004838 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004839 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4840 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4841 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004842 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4843 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004844 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4845 OutlinedFn, SharedsTy,
4846 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004847 };
4848 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4849 CodeGen);
4850 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004851 if (Data.Nogroup) {
4852 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4853 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004854 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4855 *this,
4856 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4857 PrePostActionTy &Action) {
4858 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004859 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4860 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004861 },
4862 S.getLocStart());
4863 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004864}
4865
Alexey Bataev49f6e782015-12-01 04:18:41 +00004866void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004867 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004868}
4869
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004870void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4871 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004872 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004873}
Samuel Antao686c70c2016-05-26 17:30:50 +00004874
4875// Generate the instructions for '#pragma omp target update' directive.
4876void CodeGenFunction::EmitOMPTargetUpdateDirective(
4877 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004878 // If we don't have target devices, don't bother emitting the data mapping
4879 // code.
4880 if (CGM.getLangOpts().OMPTargetTriples.empty())
4881 return;
4882
4883 // Check if we have any if clause associated with the directive.
4884 const Expr *IfCond = nullptr;
4885 if (auto *C = S.getSingleClause<OMPIfClause>())
4886 IfCond = C->getCondition();
4887
4888 // Check if we have any device clause associated with the directive.
4889 const Expr *Device = nullptr;
4890 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4891 Device = C->getDevice();
4892
Alexey Bataev475a7442018-01-12 19:39:11 +00004893 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004894 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004895}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004896
4897void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4898 const OMPExecutableDirective &D) {
4899 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4900 return;
4901 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4902 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4903 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4904 } else {
4905 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4906 for (const auto *E : LD->counters()) {
4907 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4908 cast<DeclRefExpr>(E)->getDecl())) {
4909 // Emit only those that were not explicitly referenced in clauses.
4910 if (!CGF.LocalDeclMap.count(VD))
4911 CGF.EmitVarDecl(*VD);
4912 }
4913 }
4914 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004915 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004916 }
4917 };
4918 OMPSimdLexicalScope Scope(*this, D);
4919 CGM.getOpenMPRuntime().emitInlinedDirective(
4920 *this,
4921 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4922 : D.getDirectiveKind(),
4923 CodeGen);
4924}