blob: 436a04fbeb11ce83409dc34745831abdcc630ea4 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
68 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
69 isCapturedVar(CGF, VD) ||
70 (CGF.CapturedStmtInfo &&
71 InlinedShareds.isGlobalVarCaptured(VD)),
72 VD->getType().getNonReferenceType(), VK_LValue,
73 SourceLocation());
74 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
75 return CGF.EmitLValue(&DRE).getAddress();
76 });
77 }
78 }
79 (void)InlinedShareds.Privatize();
80 }
81 }
Alexey Bataev3392d762016-02-16 11:18:12 +000082 }
83};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000084
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000085/// Lexical scope for OpenMP parallel construct, that handles correct codegen
86/// for captured expressions.
87class OMPParallelScope final : public OMPLexicalScope {
88 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
89 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000090 return !(isOpenMPTargetExecutionDirective(Kind) ||
91 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000092 isOpenMPParallelDirective(Kind);
93 }
94
95public:
96 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
97 : OMPLexicalScope(CGF, S,
98 /*AsInlined=*/false,
99 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
100};
101
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000102/// Lexical scope for OpenMP teams construct, that handles correct codegen
103/// for captured expressions.
104class OMPTeamsScope final : public OMPLexicalScope {
105 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
106 OpenMPDirectiveKind Kind = S.getDirectiveKind();
107 return !isOpenMPTargetExecutionDirective(Kind) &&
108 isOpenMPTeamsDirective(Kind);
109 }
110
111public:
112 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
113 : OMPLexicalScope(CGF, S,
114 /*AsInlined=*/false,
115 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
122 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
123 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
124 for (const auto *I : PreInits->decls())
125 CGF.EmitVarDecl(cast<VarDecl>(*I));
126 }
127 }
128 }
129
130public:
131 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
132 : CodeGenFunction::RunCleanupsScope(CGF) {
133 emitPreInitStmt(CGF, S);
134 }
135};
136
Alexey Bataev3392d762016-02-16 11:18:12 +0000137} // namespace
138
Alexey Bataev1189bd02016-01-26 12:20:39 +0000139llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
140 auto &C = getContext();
141 llvm::Value *Size = nullptr;
142 auto SizeInChars = C.getTypeSizeInChars(Ty);
143 if (SizeInChars.isZero()) {
144 // getTypeSizeInChars() returns 0 for a VLA.
145 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
146 llvm::Value *ArraySize;
147 std::tie(ArraySize, Ty) = getVLASize(VAT);
148 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
149 }
150 SizeInChars = C.getTypeSizeInChars(Ty);
151 if (SizeInChars.isZero())
152 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
153 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
154 } else
155 Size = CGM.getSize(SizeInChars);
156 return Size;
157}
158
Alexey Bataev2377fe92015-09-10 08:12:02 +0000159void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000160 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000161 const RecordDecl *RD = S.getCapturedRecordDecl();
162 auto CurField = RD->field_begin();
163 auto CurCap = S.captures().begin();
164 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
165 E = S.capture_init_end();
166 I != E; ++I, ++CurField, ++CurCap) {
167 if (CurField->hasCapturedVLAType()) {
168 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000170 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000171 } else if (CurCap->capturesThis())
172 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000173 else if (CurCap->capturesVariableByCopy()) {
174 llvm::Value *CV =
175 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
176
177 // If the field is not a pointer, we need to save the actual value
178 // and load it as a void pointer.
179 if (!CurField->getType()->isAnyPointerType()) {
180 auto &Ctx = getContext();
181 auto DstAddr = CreateMemTemp(
182 Ctx.getUIntPtrType(),
183 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
184 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
185
186 auto *SrcAddrVal = EmitScalarConversion(
187 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
188 Ctx.getPointerType(CurField->getType()), SourceLocation());
189 LValue SrcLV =
190 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
191
192 // Store the value using the source type pointer.
193 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
194
195 // Load the value using the destination type pointer.
196 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
197 }
198 CapturedVars.push_back(CV);
199 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000202 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000203 }
204}
205
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
207 StringRef Name, LValue AddrLV,
208 bool isReferenceType = false) {
209 ASTContext &Ctx = CGF.getContext();
210
211 auto *CastedPtr = CGF.EmitScalarConversion(
212 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
213 Ctx.getPointerType(DstType), SourceLocation());
214 auto TmpAddr =
215 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
216 .getAddress();
217
218 // If we are dealing with references we need to return the address of the
219 // reference instead of the reference of the value.
220 if (isReferenceType) {
221 QualType RefType = Ctx.getLValueReferenceType(DstType);
222 auto *RefVal = TmpAddr.getPointer();
223 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
224 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000225 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000226 }
227
228 return TmpAddr;
229}
230
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000231static QualType getCanonicalParamType(ASTContext &C, QualType T) {
232 if (T->isLValueReferenceType()) {
233 return C.getLValueReferenceType(
234 getCanonicalParamType(C, T.getNonReferenceType()),
235 /*SpelledAsLValue=*/false);
236 }
237 if (T->isPointerType())
238 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
239 return C.getCanonicalParamType(T);
240}
241
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000242namespace {
243 /// Contains required data for proper outlined function codegen.
244 struct FunctionOptions {
245 /// Captured statement for which the function is generated.
246 const CapturedStmt *S = nullptr;
247 /// true if cast to/from UIntPtr is required for variables captured by
248 /// value.
249 bool UIntPtrCastRequired = true;
250 /// true if only casted argumefnts must be registered as local args or VLA
251 /// sizes.
252 bool RegisterCastedArgsOnly = false;
253 /// Name of the generated function.
254 StringRef FunctionName;
255 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
256 bool RegisterCastedArgsOnly,
257 StringRef FunctionName)
258 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
259 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
260 FunctionName(FunctionName) {}
261 };
262}
263
264static std::pair<llvm::Function *, bool> emitOutlinedFunctionPrologue(
265 CodeGenFunction &CGF, FunctionArgList &Args,
266 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>>
267 &LocalAddrs,
268 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
269 &VLASizes,
270 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
271 const CapturedDecl *CD = FO.S->getCapturedDecl();
272 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000273 assert(CD->hasBody() && "missing CapturedDecl body");
274
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000275 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000276 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000277 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000278 ASTContext &Ctx = CGM.getContext();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000279 bool HasUIntPtrArgs = false;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000280 Args.append(CD->param_begin(),
281 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000282 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000283 for (auto *FD : RD->fields()) {
284 QualType ArgType = FD->getType();
285 IdentifierInfo *II = nullptr;
286 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000287
288 // If this is a capture by copy and the type is not a pointer, the outlined
289 // function argument type should be uintptr and the value properly casted to
290 // uintptr. This is necessary given that the runtime library is only able to
291 // deal with pointers. We can pass in the same way the VLA type sizes to the
292 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000293 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000294 I->capturesVariableArrayType()) {
295 HasUIntPtrArgs = true;
296 if (FO.UIntPtrCastRequired)
297 ArgType = Ctx.getUIntPtrType();
298 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000299
300 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000301 CapVar = I->getCapturedVar();
302 II = CapVar->getIdentifier();
303 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000304 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000305 else {
306 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000307 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000308 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000309 if (ArgType->isVariablyModifiedType())
310 ArgType = getCanonicalParamType(Ctx, ArgType.getNonReferenceType());
311 Args.push_back(ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +0000312 FD->getLocation(), II, ArgType,
313 ImplicitParamDecl::Other));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 ++I;
315 }
316 Args.append(
317 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
318 CD->param_end());
319
320 // Create the function declaration.
321 FunctionType::ExtInfo ExtInfo;
322 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000323 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000324 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
325
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000326 llvm::Function *F =
327 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
328 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000329 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
330 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000331 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000332
333 // Generate the function.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000334 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
335 CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000336 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000337 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000338 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000339 // If we are capturing a pointer by copy we don't need to do anything, just
340 // use the value that we get from the arguments.
341 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000342 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343 Address LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
Samuel Antao403ffd42016-07-27 22:49:49 +0000344 // If the variable is a reference we need to materialize it here.
345 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000346 Address RefAddr = CGF.CreateMemTemp(
347 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
348 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
349 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000350 LocalAddr = RefAddr;
351 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 if (!FO.RegisterCastedArgsOnly)
353 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000354 ++Cnt;
355 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000356 continue;
357 }
358
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000359 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 LValue ArgLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(Args[Cnt]),
361 Args[Cnt]->getType(), BaseInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000362 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000363 if (FO.UIntPtrCastRequired) {
364 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
365 Args[Cnt]->getName(),
366 ArgLVal),
367 FD->getType(), BaseInfo);
368 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000369 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 } else if (I->capturesVariable()) {
374 auto *Var = I->getCapturedVar();
375 QualType VarTy = Var->getType();
376 Address ArgAddr = ArgLVal.getAddress();
377 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000378 if (ArgLVal.getType()->isLValueReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000379 ArgAddr = CGF.EmitLoadOfReference(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000380 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000381 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000382 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000383 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000384 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
385 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000386 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000387 if (!FO.RegisterCastedArgsOnly) {
388 LocalAddrs.insert(
389 {Args[Cnt],
390 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
391 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000392 } else if (I->capturesVariableByCopy()) {
393 assert(!FD->getType()->isAnyPointerType() &&
394 "Not expecting a captured pointer.");
395 auto *Var = I->getCapturedVar();
396 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000397 LocalAddrs.insert(
398 {Args[Cnt],
399 {Var,
400 FO.UIntPtrCastRequired
401 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
402 ArgLVal, VarTy->isReferenceType())
403 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000404 } else {
405 // If 'this' is captured, load it into CXXThisValue.
406 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
408 .getScalarVal();
409 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000410 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000411 ++Cnt;
412 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000413 }
414
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 return {F, HasUIntPtrArgs};
416}
417
418llvm::Function *
419CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
420 assert(
421 CapturedStmtInfo &&
422 "CapturedStmtInfo should be set when generating the captured function");
423 const CapturedDecl *CD = S.getCapturedDecl();
424 // Build the argument list.
425 bool NeedWrapperFunction =
426 getDebugInfo() &&
427 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
428 FunctionArgList Args;
429 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
430 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
431 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
432 CapturedStmtInfo->getHelperName());
433 llvm::Function *F;
434 bool HasUIntPtrArgs;
435 std::tie(F, HasUIntPtrArgs) = emitOutlinedFunctionPrologue(
436 *this, Args, LocalAddrs, VLASizes, CXXThisValue, FO);
437 for (const auto &LocalAddrPair : LocalAddrs) {
438 if (LocalAddrPair.second.first) {
439 setAddrOfLocalVar(LocalAddrPair.second.first,
440 LocalAddrPair.second.second);
441 }
442 }
443 for (const auto &VLASizePair : VLASizes)
444 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000445 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000446 CapturedStmtInfo->EmitBody(*this, CD->getBody());
447 FinishFunction(CD->getBodyRBrace());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000448 if (!NeedWrapperFunction || !HasUIntPtrArgs)
449 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450
Alexey Bataev3e660702017-07-31 16:43:06 +0000451 SmallString<256> Buffer;
452 llvm::raw_svector_ostream Out(Buffer);
453 Out << "__nondebug_wrapper_" << CapturedStmtInfo->getHelperName();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000454 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataev3e660702017-07-31 16:43:06 +0000455 /*RegisterCastedArgsOnly=*/true, Out.str());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000456 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
457 WrapperCGF.disableDebugInfo();
458 Args.clear();
459 LocalAddrs.clear();
460 VLASizes.clear();
461 llvm::Function *WrapperF =
462 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
463 WrapperCGF.CXXThisValue, WrapperFO).first;
464 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
465 llvm::SmallVector<llvm::Value *, 4> CallArgs;
466 for (const auto *Arg : Args) {
467 llvm::Value *CallArg;
468 auto I = LocalAddrs.find(Arg);
469 if (I != LocalAddrs.end()) {
470 LValue LV =
471 WrapperCGF.MakeAddrLValue(I->second.second, Arg->getType(), BaseInfo);
472 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
473 } else {
474 auto EI = VLASizes.find(Arg);
475 if (EI != VLASizes.end())
476 CallArg = EI->second.second;
477 else {
478 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
479 Arg->getType(), BaseInfo);
480 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
481 }
482 }
483 CallArgs.emplace_back(CallArg);
484 }
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000485 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000486 WrapperCGF.FinishFunction();
487 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000488}
489
Alexey Bataev9959db52014-05-06 10:08:46 +0000490//===----------------------------------------------------------------------===//
491// OpenMP Directive Emission
492//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000493void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000494 Address DestAddr, Address SrcAddr, QualType OriginalType,
495 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000496 // Perform element-by-element initialization.
497 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000498
499 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000500 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000501 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
502 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
503
504 auto SrcBegin = SrcAddr.getPointer();
505 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000506 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000507 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
508 // The basic structure here is a while-do loop.
509 auto BodyBB = createBasicBlock("omp.arraycpy.body");
510 auto DoneBB = createBasicBlock("omp.arraycpy.done");
511 auto IsEmpty =
512 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
513 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000514
Alexey Bataev420d45b2015-04-14 05:11:24 +0000515 // Enter the loop body, making that address the current address.
516 auto EntryBB = Builder.GetInsertBlock();
517 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000518
519 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
520
521 llvm::PHINode *SrcElementPHI =
522 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
523 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
524 Address SrcElementCurrent =
525 Address(SrcElementPHI,
526 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
527
528 llvm::PHINode *DestElementPHI =
529 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
530 DestElementPHI->addIncoming(DestBegin, EntryBB);
531 Address DestElementCurrent =
532 Address(DestElementPHI,
533 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000534
Alexey Bataev420d45b2015-04-14 05:11:24 +0000535 // Emit copy.
536 CopyGen(DestElementCurrent, SrcElementCurrent);
537
538 // Shift the address forward by one element.
539 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000540 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000541 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000542 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000543 // Check whether we've reached the end.
544 auto Done =
545 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
546 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000547 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
548 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000549
550 // Done.
551 EmitBlock(DoneBB, /*IsFinished=*/true);
552}
553
John McCall7f416cc2015-09-08 08:05:57 +0000554void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
555 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000556 const VarDecl *SrcVD, const Expr *Copy) {
557 if (OriginalType->isArrayType()) {
558 auto *BO = dyn_cast<BinaryOperator>(Copy);
559 if (BO && BO->getOpcode() == BO_Assign) {
560 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000561 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000562 } else {
563 // For arrays with complex element types perform element by element
564 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000565 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000566 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000567 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000568 // Working with the single array element, so have to remap
569 // destination and source variables to corresponding array
570 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000571 CodeGenFunction::OMPPrivateScope Remap(*this);
572 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000573 return DestElement;
574 });
575 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000576 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000577 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000578 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000580 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000581 } else {
582 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000583 CodeGenFunction::OMPPrivateScope Remap(*this);
584 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
585 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000586 (void)Remap.Privatize();
587 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000588 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000589 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000590}
591
Alexey Bataev69c62a92015-04-15 04:52:20 +0000592bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
593 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000594 if (!HaveInsertPoint())
595 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000596 bool FirstprivateIsLastprivate = false;
597 llvm::DenseSet<const VarDecl *> Lastprivates;
598 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
599 for (const auto *D : C->varlists())
600 Lastprivates.insert(
601 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
602 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000603 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000604 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000605 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000606 auto IRef = C->varlist_begin();
607 auto InitsRef = C->inits().begin();
608 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000609 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000610 bool ThisFirstprivateIsLastprivate =
611 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000612 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000613 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000614 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000615 !FD->getType()->isReferenceType()) {
616 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
617 ++IRef;
618 ++InitsRef;
619 continue;
620 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000621 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000622 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000623 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000624 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
625 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
626 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000627 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
628 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
629 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000631 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000632 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000633 // Emit VarDecl with copy init for arrays.
634 // Get the address of the original variable captured in current
635 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000636 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000637 auto Emission = EmitAutoVarAlloca(*VD);
638 auto *Init = VD->getInit();
639 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
640 // Perform simple memcpy.
641 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000642 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000643 } else {
644 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000645 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000646 [this, VDInit, Init](Address DestElement,
647 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000648 // Clean up any temporaries needed by the initialization.
649 RunCleanupsScope InitScope(*this);
650 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000651 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000652 EmitAnyExprToMem(Init, DestElement,
653 Init->getType().getQualifiers(),
654 /*IsInitializer*/ false);
655 LocalDeclMap.erase(VDInit);
656 });
657 }
658 EmitAutoVarCleanups(Emission);
659 return Emission.getAllocatedAddress();
660 });
661 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000662 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000663 // Emit private VarDecl with copy init.
664 // Remap temp VDInit variable to the address of the original
665 // variable
666 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000667 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000668 EmitDecl(*VD);
669 LocalDeclMap.erase(VDInit);
670 return GetAddrOfLocalVar(VD);
671 });
672 }
673 assert(IsRegistered &&
674 "firstprivate var already registered as private");
675 // Silence the warning about unused variable.
676 (void)IsRegistered;
677 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000678 ++IRef;
679 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000680 }
681 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000682 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000683}
684
Alexey Bataev03b340a2014-10-21 03:16:40 +0000685void CodeGenFunction::EmitOMPPrivateClause(
686 const OMPExecutableDirective &D,
687 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000688 if (!HaveInsertPoint())
689 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000690 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000691 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000692 auto IRef = C->varlist_begin();
693 for (auto IInit : C->private_copies()) {
694 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000695 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
696 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
697 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000698 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000699 // Emit private VarDecl with copy init.
700 EmitDecl(*VD);
701 return GetAddrOfLocalVar(VD);
702 });
703 assert(IsRegistered && "private var already registered as private");
704 // Silence the warning about unused variable.
705 (void)IsRegistered;
706 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000707 ++IRef;
708 }
709 }
710}
711
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000712bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000713 if (!HaveInsertPoint())
714 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000715 // threadprivate_var1 = master_threadprivate_var1;
716 // operator=(threadprivate_var2, master_threadprivate_var2);
717 // ...
718 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000719 llvm::DenseSet<const VarDecl *> CopiedVars;
720 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000721 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000722 auto IRef = C->varlist_begin();
723 auto ISrcRef = C->source_exprs().begin();
724 auto IDestRef = C->destination_exprs().begin();
725 for (auto *AssignOp : C->assignment_ops()) {
726 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000727 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000728 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000729 // Get the address of the master variable. If we are emitting code with
730 // TLS support, the address is passed from the master as field in the
731 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000732 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000733 if (getLangOpts().OpenMPUseTLS &&
734 getContext().getTargetInfo().isTLSSupported()) {
735 assert(CapturedStmtInfo->lookup(VD) &&
736 "Copyin threadprivates should have been captured!");
737 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
738 VK_LValue, (*IRef)->getExprLoc());
739 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000740 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000741 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000742 MasterAddr =
743 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
744 : CGM.GetAddrOfGlobal(VD),
745 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000746 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000747 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000748 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000749 if (CopiedVars.size() == 1) {
750 // At first check if current thread is a master thread. If it is, no
751 // need to copy data.
752 CopyBegin = createBasicBlock("copyin.not.master");
753 CopyEnd = createBasicBlock("copyin.not.master.end");
754 Builder.CreateCondBr(
755 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000756 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
757 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000758 CopyBegin, CopyEnd);
759 EmitBlock(CopyBegin);
760 }
761 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
762 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000763 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000764 }
765 ++IRef;
766 ++ISrcRef;
767 ++IDestRef;
768 }
769 }
770 if (CopyEnd) {
771 // Exit out of copying procedure for non-master thread.
772 EmitBlock(CopyEnd, /*IsFinished=*/true);
773 return true;
774 }
775 return false;
776}
777
Alexey Bataev38e89532015-04-16 04:54:05 +0000778bool CodeGenFunction::EmitOMPLastprivateClauseInit(
779 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000780 if (!HaveInsertPoint())
781 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000782 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000783 llvm::DenseSet<const VarDecl *> SIMDLCVs;
784 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
785 auto *LoopDirective = cast<OMPLoopDirective>(&D);
786 for (auto *C : LoopDirective->counters()) {
787 SIMDLCVs.insert(
788 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
789 }
790 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000791 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000792 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000793 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000794 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
795 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000796 auto IRef = C->varlist_begin();
797 auto IDestRef = C->destination_exprs().begin();
798 for (auto *IInit : C->private_copies()) {
799 // Keep the address of the original variable for future update at the end
800 // of the loop.
801 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000802 // Taskloops do not require additional initialization, it is done in
803 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000804 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
805 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000806 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000807 DeclRefExpr DRE(
808 const_cast<VarDecl *>(OrigVD),
809 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
810 OrigVD) != nullptr,
811 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
812 return EmitLValue(&DRE).getAddress();
813 });
814 // Check if the variable is also a firstprivate: in this case IInit is
815 // not generated. Initialization of this variable will happen in codegen
816 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000817 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000818 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000819 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
820 // Emit private VarDecl with copy init.
821 EmitDecl(*VD);
822 return GetAddrOfLocalVar(VD);
823 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000824 assert(IsRegistered &&
825 "lastprivate var already registered as private");
826 (void)IsRegistered;
827 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000828 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000829 ++IRef;
830 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000831 }
832 }
833 return HasAtLeastOneLastprivate;
834}
835
836void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000837 const OMPExecutableDirective &D, bool NoFinals,
838 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000839 if (!HaveInsertPoint())
840 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000841 // Emit following code:
842 // if (<IsLastIterCond>) {
843 // orig_var1 = private_orig_var1;
844 // ...
845 // orig_varn = private_orig_varn;
846 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000847 llvm::BasicBlock *ThenBB = nullptr;
848 llvm::BasicBlock *DoneBB = nullptr;
849 if (IsLastIterCond) {
850 ThenBB = createBasicBlock(".omp.lastprivate.then");
851 DoneBB = createBasicBlock(".omp.lastprivate.done");
852 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
853 EmitBlock(ThenBB);
854 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000855 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
856 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000857 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000858 auto IC = LoopDirective->counters().begin();
859 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000860 auto *D =
861 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
862 if (NoFinals)
863 AlreadyEmittedVars.insert(D);
864 else
865 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000866 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000867 }
868 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000869 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
870 auto IRef = C->varlist_begin();
871 auto ISrcRef = C->source_exprs().begin();
872 auto IDestRef = C->destination_exprs().begin();
873 for (auto *AssignOp : C->assignment_ops()) {
874 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
875 QualType Type = PrivateVD->getType();
876 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
877 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
878 // If lastprivate variable is a loop control variable for loop-based
879 // directive, update its value before copyin back to original
880 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000881 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
882 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000883 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
884 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
885 // Get the address of the original variable.
886 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
887 // Get the address of the private variable.
888 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
889 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
890 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000891 Address(Builder.CreateLoad(PrivateAddr),
892 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000893 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000894 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000895 ++IRef;
896 ++ISrcRef;
897 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000898 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000899 if (auto *PostUpdate = C->getPostUpdateExpr())
900 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000901 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000902 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000903 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000904}
905
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000906void CodeGenFunction::EmitOMPReductionClauseInit(
907 const OMPExecutableDirective &D,
908 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000909 if (!HaveInsertPoint())
910 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000911 SmallVector<const Expr *, 4> Shareds;
912 SmallVector<const Expr *, 4> Privates;
913 SmallVector<const Expr *, 4> ReductionOps;
914 SmallVector<const Expr *, 4> LHSs;
915 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000916 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000917 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000918 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919 auto ILHS = C->lhs_exprs().begin();
920 auto IRHS = C->rhs_exprs().begin();
921 for (const auto *Ref : C->varlists()) {
922 Shareds.emplace_back(Ref);
923 Privates.emplace_back(*IPriv);
924 ReductionOps.emplace_back(*IRed);
925 LHSs.emplace_back(*ILHS);
926 RHSs.emplace_back(*IRHS);
927 std::advance(IPriv, 1);
928 std::advance(IRed, 1);
929 std::advance(ILHS, 1);
930 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000931 }
932 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
934 unsigned Count = 0;
935 auto ILHS = LHSs.begin();
936 auto IRHS = RHSs.begin();
937 auto IPriv = Privates.begin();
938 for (const auto *IRef : Shareds) {
939 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
940 // Emit private VarDecl with reduction init.
941 RedCG.emitSharedLValue(*this, Count);
942 RedCG.emitAggregateType(*this, Count);
943 auto Emission = EmitAutoVarAlloca(*PrivateVD);
944 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
945 RedCG.getSharedLValue(Count),
946 [&Emission](CodeGenFunction &CGF) {
947 CGF.EmitAutoVarInit(Emission);
948 return true;
949 });
950 EmitAutoVarCleanups(Emission);
951 Address BaseAddr = RedCG.adjustPrivateAddress(
952 *this, Count, Emission.getAllocatedAddress());
953 bool IsRegistered = PrivateScope.addPrivate(
954 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
955 assert(IsRegistered && "private var already registered as private");
956 // Silence the warning about unused variable.
957 (void)IsRegistered;
958
959 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
960 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Eric Christopher7aba9782017-07-14 01:42:57 +0000961 if (isa<OMPArraySectionExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 // Store the address of the original variable associated with the LHS
963 // implicit variable.
964 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
965 return RedCG.getSharedLValue(Count).getAddress();
966 });
967 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
968 return GetAddrOfLocalVar(PrivateVD);
969 });
Eric Christopher7aba9782017-07-14 01:42:57 +0000970 } else if (isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000971 // Store the address of the original variable associated with the LHS
972 // implicit variable.
973 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
974 return RedCG.getSharedLValue(Count).getAddress();
975 });
976 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
977 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
978 ConvertTypeForMem(RHSVD->getType()),
979 "rhs.begin");
980 });
981 } else {
982 QualType Type = PrivateVD->getType();
983 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
984 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
985 // Store the address of the original variable associated with the LHS
986 // implicit variable.
987 if (IsArray) {
988 OriginalAddr = Builder.CreateElementBitCast(
989 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
990 }
991 PrivateScope.addPrivate(
992 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
993 PrivateScope.addPrivate(
994 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
995 return IsArray
996 ? Builder.CreateElementBitCast(
997 GetAddrOfLocalVar(PrivateVD),
998 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
999 : GetAddrOfLocalVar(PrivateVD);
1000 });
1001 }
1002 ++ILHS;
1003 ++IRHS;
1004 ++IPriv;
1005 ++Count;
1006 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001007}
1008
1009void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001010 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001011 if (!HaveInsertPoint())
1012 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001013 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001014 llvm::SmallVector<const Expr *, 8> LHSExprs;
1015 llvm::SmallVector<const Expr *, 8> RHSExprs;
1016 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001017 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001018 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001019 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001020 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001021 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1022 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1023 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1024 }
1025 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001026 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1027 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1028 D.getDirectiveKind() == OMPD_simd;
1029 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001030 // Emit nowait reduction if nowait clause is present or directive is a
1031 // parallel directive (it always has implicit barrier).
1032 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001033 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001034 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001035 }
1036}
1037
Alexey Bataev61205072016-03-02 04:57:40 +00001038static void emitPostUpdateForReductionClause(
1039 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1040 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1041 if (!CGF.HaveInsertPoint())
1042 return;
1043 llvm::BasicBlock *DoneBB = nullptr;
1044 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1045 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1046 if (!DoneBB) {
1047 if (auto *Cond = CondGen(CGF)) {
1048 // If the first post-update expression is found, emit conditional
1049 // block if it was requested.
1050 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1051 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1052 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1053 CGF.EmitBlock(ThenBB);
1054 }
1055 }
1056 CGF.EmitIgnoredExpr(PostUpdate);
1057 }
1058 }
1059 if (DoneBB)
1060 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1061}
1062
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001063namespace {
1064/// Codegen lambda for appending distribute lower and upper bounds to outlined
1065/// parallel function. This is necessary for combined constructs such as
1066/// 'distribute parallel for'
1067typedef llvm::function_ref<void(CodeGenFunction &,
1068 const OMPExecutableDirective &,
1069 llvm::SmallVectorImpl<llvm::Value *> &)>
1070 CodeGenBoundParametersTy;
1071} // anonymous namespace
1072
1073static void emitCommonOMPParallelDirective(
1074 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1075 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1076 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001077 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1078 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1079 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001080 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001081 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001082 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1083 /*IgnoreResultAssign*/ true);
1084 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1085 CGF, NumThreads, NumThreadsClause->getLocStart());
1086 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001087 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001088 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001089 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1090 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1091 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001092 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001093 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1094 if (C->getNameModifier() == OMPD_unknown ||
1095 C->getNameModifier() == OMPD_parallel) {
1096 IfCond = C->getCondition();
1097 break;
1098 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001099 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001100
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001101 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001102 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001103 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1104 // lower and upper bounds with the pragma 'for' chunking mechanism.
1105 // The following lambda takes care of appending the lower and upper bound
1106 // parameters when necessary
1107 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001108 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001109 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001110 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001111}
1112
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001113static void emitEmptyBoundParameters(CodeGenFunction &,
1114 const OMPExecutableDirective &,
1115 llvm::SmallVectorImpl<llvm::Value *> &) {}
1116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001117void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001118 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001119 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001120 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001121 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001122 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1123 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001124 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001125 // propagation master's thread values of threadprivate variables to local
1126 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001127 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1128 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1129 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001130 }
1131 CGF.EmitOMPPrivateClause(S, PrivateScope);
1132 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1133 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001135 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001136 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001137 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1138 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001139 emitPostUpdateForReductionClause(
1140 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001141}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001142
Alexey Bataev0f34da12015-07-02 04:17:07 +00001143void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1144 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001145 RunCleanupsScope BodyScope(*this);
1146 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001147 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001148 EmitIgnoredExpr(I);
1149 }
Alexander Musman3276a272015-03-21 10:12:56 +00001150 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001151 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001152 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001153 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001154 }
1155
Alexander Musmana5f070a2014-10-01 06:03:56 +00001156 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001157 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001158 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001159 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001160 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001161 // The end (updates/cleanups).
1162 EmitBlock(Continue.getBlock());
1163 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001164}
1165
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001166void CodeGenFunction::EmitOMPInnerLoop(
1167 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1168 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001169 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1170 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001171 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001172
1173 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001174 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001175 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001176 const SourceRange &R = S.getSourceRange();
1177 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1178 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001179
1180 // If there are any cleanups between here and the loop-exit scope,
1181 // create a block to stage a loop exit along.
1182 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001183 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001184 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001185
Alexander Musmand196ef22014-10-07 08:57:09 +00001186 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001187
Alexey Bataev2df54a02015-03-12 08:53:29 +00001188 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001189 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001190 if (ExitBlock != LoopExit.getBlock()) {
1191 EmitBlock(ExitBlock);
1192 EmitBranchThroughCleanup(LoopExit);
1193 }
1194
1195 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001196 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001197
1198 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001199 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001200 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1201
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001202 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001203
1204 // Emit "IV = IV + 1" and a back-edge to the condition block.
1205 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001206 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001207 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001208 BreakContinueStack.pop_back();
1209 EmitBranch(CondBlock);
1210 LoopStack.pop();
1211 // Emit the fall-through block.
1212 EmitBlock(LoopExit.getBlock());
1213}
1214
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001215void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001216 if (!HaveInsertPoint())
1217 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001218 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001219 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001220 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001221 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001222 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1223 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1224 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1226 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1227 VD->getInit()->getType(), VK_LValue,
1228 VD->getInit()->getExprLoc());
1229 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1230 VD->getType()),
1231 /*capturedByInit=*/false);
1232 EmitAutoVarCleanups(Emission);
1233 } else
1234 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001235 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001236 // Emit the linear steps for the linear clauses.
1237 // If a step is not constant, it is pre-calculated before the loop.
1238 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1239 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001240 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001241 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001242 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001243 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001244 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001245}
1246
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001247void CodeGenFunction::EmitOMPLinearClauseFinal(
1248 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001249 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001250 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001251 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001252 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001253 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001254 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001255 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001256 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001257 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001258 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001259 // If the first post-update expression is found, emit conditional
1260 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001261 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1262 DoneBB = createBasicBlock(".omp.linear.pu.done");
1263 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1264 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001265 }
1266 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001267 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1268 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001269 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001270 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001271 Address OrigAddr = EmitLValue(&DRE).getAddress();
1272 CodeGenFunction::OMPPrivateScope VarScope(*this);
1273 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001274 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001275 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001276 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001277 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001278 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001279 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001280 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001281 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001282 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283}
1284
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001285static void emitAlignedClause(CodeGenFunction &CGF,
1286 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001287 if (!CGF.HaveInsertPoint())
1288 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001289 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001290 unsigned ClauseAlignment = 0;
1291 if (auto AlignmentExpr = Clause->getAlignment()) {
1292 auto AlignmentCI =
1293 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1294 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001295 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001296 for (auto E : Clause->varlists()) {
1297 unsigned Alignment = ClauseAlignment;
1298 if (Alignment == 0) {
1299 // OpenMP [2.8.1, Description]
1300 // If no optional parameter is specified, implementation-defined default
1301 // alignments for SIMD instructions on the target platforms are assumed.
1302 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001303 CGF.getContext()
1304 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1305 E->getType()->getPointeeType()))
1306 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001307 }
1308 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1309 "alignment is not power of 2");
1310 if (Alignment != 0) {
1311 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1312 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1313 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001314 }
1315 }
1316}
1317
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001318void CodeGenFunction::EmitOMPPrivateLoopCounters(
1319 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1320 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001321 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001322 auto I = S.private_counters().begin();
1323 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001324 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1325 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001326 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001327 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 if (!LocalDeclMap.count(PrivateVD)) {
1329 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1330 EmitAutoVarCleanups(VarEmission);
1331 }
1332 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1333 /*RefersToEnclosingVariableOrCapture=*/false,
1334 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1335 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001336 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001337 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1338 VD->hasGlobalStorage()) {
1339 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1340 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1341 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1342 E->getType(), VK_LValue, E->getExprLoc());
1343 return EmitLValue(&DRE).getAddress();
1344 });
1345 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001346 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001347 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001348}
1349
Alexey Bataev62dbb972015-04-22 11:59:37 +00001350static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1351 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1352 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001353 if (!CGF.HaveInsertPoint())
1354 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001355 {
1356 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001357 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001358 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001359 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001360 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001361 CGF.EmitIgnoredExpr(I);
1362 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001363 }
1364 // Check that loop is executed at least one time.
1365 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1366}
1367
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001368void CodeGenFunction::EmitOMPLinearClause(
1369 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1370 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001371 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001372 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1373 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1374 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1375 for (auto *C : LoopDirective->counters()) {
1376 SIMDLCVs.insert(
1377 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1378 }
1379 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001380 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001381 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001382 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001383 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1384 auto *PrivateVD =
1385 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001386 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1387 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1388 // Emit private VarDecl with copy init.
1389 EmitVarDecl(*PrivateVD);
1390 return GetAddrOfLocalVar(PrivateVD);
1391 });
1392 assert(IsRegistered && "linear var already registered as private");
1393 // Silence the warning about unused variable.
1394 (void)IsRegistered;
1395 } else
1396 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001397 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001398 }
1399 }
1400}
1401
Alexey Bataev45bfad52015-08-21 12:19:04 +00001402static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001403 const OMPExecutableDirective &D,
1404 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001405 if (!CGF.HaveInsertPoint())
1406 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001407 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001408 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1409 /*ignoreResult=*/true);
1410 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1411 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1412 // In presence of finite 'safelen', it may be unsafe to mark all
1413 // the memory instructions parallel, because loop-carried
1414 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001415 if (!IsMonotonic)
1416 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001417 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001418 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1419 /*ignoreResult=*/true);
1420 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001421 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001422 // In presence of finite 'safelen', it may be unsafe to mark all
1423 // the memory instructions parallel, because loop-carried
1424 // dependences of 'safelen' iterations are possible.
1425 CGF.LoopStack.setParallel(false);
1426 }
1427}
1428
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001429void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1430 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001431 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001432 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001433 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001434 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001435}
1436
Alexey Bataevef549a82016-03-09 09:49:09 +00001437void CodeGenFunction::EmitOMPSimdFinal(
1438 const OMPLoopDirective &D,
1439 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001440 if (!HaveInsertPoint())
1441 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001442 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001443 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001444 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001445 for (auto F : D.finals()) {
1446 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001447 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1448 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1449 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1450 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001451 if (!DoneBB) {
1452 if (auto *Cond = CondGen(*this)) {
1453 // If the first post-update expression is found, emit conditional
1454 // block if it was requested.
1455 auto *ThenBB = createBasicBlock(".omp.final.then");
1456 DoneBB = createBasicBlock(".omp.final.done");
1457 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1458 EmitBlock(ThenBB);
1459 }
1460 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001461 Address OrigAddr = Address::invalid();
1462 if (CED)
1463 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1464 else {
1465 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1466 /*RefersToEnclosingVariableOrCapture=*/false,
1467 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1468 OrigAddr = EmitLValue(&DRE).getAddress();
1469 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001470 OMPPrivateScope VarScope(*this);
1471 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001472 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001473 (void)VarScope.Privatize();
1474 EmitIgnoredExpr(F);
1475 }
1476 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001477 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001478 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001479 if (DoneBB)
1480 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001481}
1482
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001483static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1484 const OMPLoopDirective &S,
1485 CodeGenFunction::JumpDest LoopExit) {
1486 CGF.EmitOMPLoopBody(S, LoopExit);
1487 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001488}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001489
Alexander Musman515ad8c2014-05-22 08:54:05 +00001490void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001491 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001492 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001493 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001494 // for (IV in 0..LastIteration) BODY;
1495 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001496 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001497 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001498
Alexey Bataev62dbb972015-04-22 11:59:37 +00001499 // Emit: if (PreCond) - begin.
1500 // If the condition constant folds and can be elided, avoid emitting the
1501 // whole loop.
1502 bool CondConstant;
1503 llvm::BasicBlock *ContBlock = nullptr;
1504 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1505 if (!CondConstant)
1506 return;
1507 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001508 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1509 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001510 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1511 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001512 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001513 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001514 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001515
1516 // Emit the loop iteration variable.
1517 const Expr *IVExpr = S.getIterationVariable();
1518 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1519 CGF.EmitVarDecl(*IVDecl);
1520 CGF.EmitIgnoredExpr(S.getInit());
1521
1522 // Emit the iterations count variable.
1523 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001524 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001525 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1526 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1527 // Emit calculation of the iterations count.
1528 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001529 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001530
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001531 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001532
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001533 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001534 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001535 {
1536 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001537 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1538 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001539 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001540 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001541 bool HasLastprivateClause =
1542 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001543 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001544 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1545 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001546 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001547 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001548 CGF.EmitStopPoint(&S);
1549 },
1550 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001551 CGF.EmitOMPSimdFinal(
1552 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001553 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001554 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001555 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001556 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001557 emitPostUpdateForReductionClause(
1558 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001559 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001561 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001562 // Emit: if (PreCond) - end.
1563 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001564 CGF.EmitBranch(ContBlock);
1565 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001566 }
1567 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001568 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001569 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001570}
1571
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001572void CodeGenFunction::EmitOMPOuterLoop(
1573 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1574 CodeGenFunction::OMPPrivateScope &LoopScope,
1575 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1576 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1577 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001578 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001579
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001580 const Expr *IVExpr = S.getIterationVariable();
1581 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1582 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1583
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001584 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1585
1586 // Start the loop with a block that tests the condition.
1587 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1588 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001589 const SourceRange &R = S.getSourceRange();
1590 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1591 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001592
1593 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001594 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001595 // UB = min(UB, GlobalUB) or
1596 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1597 // 'distribute parallel for')
1598 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001599 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001600 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001601 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001602 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001603 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001604 BoolCondVal =
1605 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1606 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001607 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001608
1609 // If there are any cleanups between here and the loop-exit scope,
1610 // create a block to stage a loop exit along.
1611 auto ExitBlock = LoopExit.getBlock();
1612 if (LoopScope.requiresCleanups())
1613 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1614
1615 auto LoopBody = createBasicBlock("omp.dispatch.body");
1616 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1617 if (ExitBlock != LoopExit.getBlock()) {
1618 EmitBlock(ExitBlock);
1619 EmitBranchThroughCleanup(LoopExit);
1620 }
1621 EmitBlock(LoopBody);
1622
Alexander Musman92bdaab2015-03-12 13:37:50 +00001623 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1624 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001625 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001626 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001627
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001628 // Create a block for the increment.
1629 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1630 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1631
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1633 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001634 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1635 LoopStack.setParallel(!IsMonotonic);
1636 else
1637 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001638
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001639 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001640
1641 // when 'distribute' is not combined with a 'for':
1642 // while (idx <= UB) { BODY; ++idx; }
1643 // when 'distribute' is combined with a 'for'
1644 // (e.g. 'distribute parallel for')
1645 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1646 EmitOMPInnerLoop(
1647 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1648 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1649 CodeGenLoop(CGF, S, LoopExit);
1650 },
1651 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1652 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1653 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001654
1655 EmitBlock(Continue.getBlock());
1656 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001657 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001658 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001659 EmitIgnoredExpr(LoopArgs.NextLB);
1660 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001661 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001662
1663 EmitBranch(CondBlock);
1664 LoopStack.pop();
1665 // Emit the fall-through block.
1666 EmitBlock(LoopExit.getBlock());
1667
1668 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001669 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1670 if (!DynamicOrOrdered)
1671 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1672 };
1673 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001674}
1675
1676void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001677 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001678 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001679 const OMPLoopArguments &LoopArgs,
1680 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001681 auto &RT = CGM.getOpenMPRuntime();
1682
1683 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001684 const bool DynamicOrOrdered =
1685 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001686
1687 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001688 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001689 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001690 "static non-chunked schedule does not need outer loop");
1691
1692 // Emit outer loop.
1693 //
1694 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1695 // When schedule(dynamic,chunk_size) is specified, the iterations are
1696 // distributed to threads in the team in chunks as the threads request them.
1697 // Each thread executes a chunk of iterations, then requests another chunk,
1698 // until no chunks remain to be distributed. Each chunk contains chunk_size
1699 // iterations, except for the last chunk to be distributed, which may have
1700 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1701 //
1702 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1703 // to threads in the team in chunks as the executing threads request them.
1704 // Each thread executes a chunk of iterations, then requests another chunk,
1705 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1706 // each chunk is proportional to the number of unassigned iterations divided
1707 // by the number of threads in the team, decreasing to 1. For a chunk_size
1708 // with value k (greater than 1), the size of each chunk is determined in the
1709 // same way, with the restriction that the chunks do not contain fewer than k
1710 // iterations (except for the last chunk to be assigned, which may have fewer
1711 // than k iterations).
1712 //
1713 // When schedule(auto) is specified, the decision regarding scheduling is
1714 // delegated to the compiler and/or runtime system. The programmer gives the
1715 // implementation the freedom to choose any possible mapping of iterations to
1716 // threads in the team.
1717 //
1718 // When schedule(runtime) is specified, the decision regarding scheduling is
1719 // deferred until run time, and the schedule and chunk size are taken from the
1720 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1721 // implementation defined
1722 //
1723 // while(__kmpc_dispatch_next(&LB, &UB)) {
1724 // idx = LB;
1725 // while (idx <= UB) { BODY; ++idx;
1726 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1727 // } // inner loop
1728 // }
1729 //
1730 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1731 // When schedule(static, chunk_size) is specified, iterations are divided into
1732 // chunks of size chunk_size, and the chunks are assigned to the threads in
1733 // the team in a round-robin fashion in the order of the thread number.
1734 //
1735 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1736 // while (idx <= UB) { BODY; ++idx; } // inner loop
1737 // LB = LB + ST;
1738 // UB = UB + ST;
1739 // }
1740 //
1741
1742 const Expr *IVExpr = S.getIterationVariable();
1743 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1744 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1745
1746 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001747 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1748 llvm::Value *LBVal = DispatchBounds.first;
1749 llvm::Value *UBVal = DispatchBounds.second;
1750 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1751 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001752 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001753 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001754 } else {
1755 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001756 Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1757 LoopArgs.ST, LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001758 }
1759
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001760 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1761 const unsigned IVSize,
1762 const bool IVSigned) {
1763 if (Ordered) {
1764 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1765 IVSigned);
1766 }
1767 };
1768
1769 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1770 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1771 OuterLoopArgs.IncExpr = S.getInc();
1772 OuterLoopArgs.Init = S.getInit();
1773 OuterLoopArgs.Cond = S.getCond();
1774 OuterLoopArgs.NextLB = S.getNextLowerBound();
1775 OuterLoopArgs.NextUB = S.getNextUpperBound();
1776 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1777 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001778}
1779
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001780static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1781 const unsigned IVSize, const bool IVSigned) {}
1782
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001783void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001784 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1785 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1786 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001787
1788 auto &RT = CGM.getOpenMPRuntime();
1789
1790 // Emit outer loop.
1791 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1792 // dynamic
1793 //
1794
1795 const Expr *IVExpr = S.getIterationVariable();
1796 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1797 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1798
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001799 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1800 IVSigned, /* Ordered = */ false, LoopArgs.IL,
1801 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1802 LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001803
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001804 // for combined 'distribute' and 'for' the increment expression of distribute
1805 // is store in DistInc. For 'distribute' alone, it is in Inc.
1806 Expr *IncExpr;
1807 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1808 IncExpr = S.getDistInc();
1809 else
1810 IncExpr = S.getInc();
1811
1812 // this routine is shared by 'omp distribute parallel for' and
1813 // 'omp distribute': select the right EUB expression depending on the
1814 // directive
1815 OMPLoopArguments OuterLoopArgs;
1816 OuterLoopArgs.LB = LoopArgs.LB;
1817 OuterLoopArgs.UB = LoopArgs.UB;
1818 OuterLoopArgs.ST = LoopArgs.ST;
1819 OuterLoopArgs.IL = LoopArgs.IL;
1820 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1821 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1822 ? S.getCombinedEnsureUpperBound()
1823 : S.getEnsureUpperBound();
1824 OuterLoopArgs.IncExpr = IncExpr;
1825 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1826 ? S.getCombinedInit()
1827 : S.getInit();
1828 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1829 ? S.getCombinedCond()
1830 : S.getCond();
1831 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1832 ? S.getCombinedNextLowerBound()
1833 : S.getNextLowerBound();
1834 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1835 ? S.getCombinedNextUpperBound()
1836 : S.getNextUpperBound();
1837
1838 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1839 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1840 emitEmptyOrdered);
1841}
1842
1843/// Emit a helper variable and return corresponding lvalue.
1844static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1845 const DeclRefExpr *Helper) {
1846 auto VDecl = cast<VarDecl>(Helper->getDecl());
1847 CGF.EmitVarDecl(*VDecl);
1848 return CGF.EmitLValue(Helper);
1849}
1850
1851static std::pair<LValue, LValue>
1852emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1853 const OMPExecutableDirective &S) {
1854 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1855 LValue LB =
1856 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1857 LValue UB =
1858 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1859
1860 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1861 // parallel for') we need to use the 'distribute'
1862 // chunk lower and upper bounds rather than the whole loop iteration
1863 // space. These are parameters to the outlined function for 'parallel'
1864 // and we copy the bounds of the previous schedule into the
1865 // the current ones.
1866 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1867 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1868 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1869 PrevLBVal = CGF.EmitScalarConversion(
1870 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1871 LS.getIterationVariable()->getType(), SourceLocation());
1872 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1873 PrevUBVal = CGF.EmitScalarConversion(
1874 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1875 LS.getIterationVariable()->getType(), SourceLocation());
1876
1877 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1878 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1879
1880 return {LB, UB};
1881}
1882
1883/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1884/// we need to use the LB and UB expressions generated by the worksharing
1885/// code generation support, whereas in non combined situations we would
1886/// just emit 0 and the LastIteration expression
1887/// This function is necessary due to the difference of the LB and UB
1888/// types for the RT emission routines for 'for_static_init' and
1889/// 'for_dispatch_init'
1890static std::pair<llvm::Value *, llvm::Value *>
1891emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1892 const OMPExecutableDirective &S,
1893 Address LB, Address UB) {
1894 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1895 const Expr *IVExpr = LS.getIterationVariable();
1896 // when implementing a dynamic schedule for a 'for' combined with a
1897 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1898 // is not normalized as each team only executes its own assigned
1899 // distribute chunk
1900 QualType IteratorTy = IVExpr->getType();
1901 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1902 SourceLocation());
1903 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1904 SourceLocation());
1905 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001906}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001907
1908static void emitDistributeParallelForDistributeInnerBoundParams(
1909 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1910 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1911 const auto &Dir = cast<OMPLoopDirective>(S);
1912 LValue LB =
1913 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1914 auto LBCast = CGF.Builder.CreateIntCast(
1915 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1916 CapturedVars.push_back(LBCast);
1917 LValue UB =
1918 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1919
1920 auto UBCast = CGF.Builder.CreateIntCast(
1921 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1922 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001923}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001924
1925static void
1926emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1927 const OMPLoopDirective &S,
1928 CodeGenFunction::JumpDest LoopExit) {
1929 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1930 PrePostActionTy &) {
1931 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1932 emitDistributeParallelForInnerBounds,
1933 emitDistributeParallelForDispatchBounds);
1934 };
1935
1936 emitCommonOMPParallelDirective(
1937 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
1938 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001939}
1940
Carlo Bertolli9925f152016-06-27 14:55:37 +00001941void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1942 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001943 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1944 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
1945 S.getDistInc());
1946 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00001947 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001948 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
1949 /*HasCancel=*/false);
1950 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
1951 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001952}
1953
Kelvin Li4a39add2016-07-05 05:00:15 +00001954void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1955 const OMPDistributeParallelForSimdDirective &S) {
1956 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1957 CGM.getOpenMPRuntime().emitInlinedDirective(
1958 *this, OMPD_distribute_parallel_for_simd,
1959 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1960 OMPLoopScope PreInitScope(CGF, S);
1961 CGF.EmitStmt(
1962 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1963 });
1964}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001965
1966void CodeGenFunction::EmitOMPDistributeSimdDirective(
1967 const OMPDistributeSimdDirective &S) {
1968 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1969 CGM.getOpenMPRuntime().emitInlinedDirective(
1970 *this, OMPD_distribute_simd,
1971 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1972 OMPLoopScope PreInitScope(CGF, S);
1973 CGF.EmitStmt(
1974 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1975 });
1976}
1977
Kelvin Lia579b912016-07-14 02:54:56 +00001978void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1979 const OMPTargetParallelForSimdDirective &S) {
1980 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1981 CGM.getOpenMPRuntime().emitInlinedDirective(
1982 *this, OMPD_target_parallel_for_simd,
1983 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1984 OMPLoopScope PreInitScope(CGF, S);
1985 CGF.EmitStmt(
1986 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1987 });
1988}
1989
Kelvin Li986330c2016-07-20 22:57:10 +00001990void CodeGenFunction::EmitOMPTargetSimdDirective(
1991 const OMPTargetSimdDirective &S) {
1992 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1993 CGM.getOpenMPRuntime().emitInlinedDirective(
1994 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1995 OMPLoopScope PreInitScope(CGF, S);
1996 CGF.EmitStmt(
1997 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1998 });
1999}
2000
Kelvin Li02532872016-08-05 14:37:37 +00002001void CodeGenFunction::EmitOMPTeamsDistributeDirective(
2002 const OMPTeamsDistributeDirective &S) {
2003 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2004 CGM.getOpenMPRuntime().emitInlinedDirective(
2005 *this, OMPD_teams_distribute,
2006 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2007 OMPLoopScope PreInitScope(CGF, S);
2008 CGF.EmitStmt(
2009 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2010 });
2011}
2012
Kelvin Li4e325f72016-10-25 12:50:55 +00002013void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2014 const OMPTeamsDistributeSimdDirective &S) {
2015 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2016 CGM.getOpenMPRuntime().emitInlinedDirective(
2017 *this, OMPD_teams_distribute_simd,
2018 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2019 OMPLoopScope PreInitScope(CGF, S);
2020 CGF.EmitStmt(
2021 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2022 });
2023}
2024
Kelvin Li579e41c2016-11-30 23:51:03 +00002025void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2026 const OMPTeamsDistributeParallelForSimdDirective &S) {
2027 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2028 CGM.getOpenMPRuntime().emitInlinedDirective(
2029 *this, OMPD_teams_distribute_parallel_for_simd,
2030 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2031 OMPLoopScope PreInitScope(CGF, S);
2032 CGF.EmitStmt(
2033 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2034 });
2035}
Kelvin Li4e325f72016-10-25 12:50:55 +00002036
Kelvin Li7ade93f2016-12-09 03:24:30 +00002037void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2038 const OMPTeamsDistributeParallelForDirective &S) {
2039 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2040 CGM.getOpenMPRuntime().emitInlinedDirective(
2041 *this, OMPD_teams_distribute_parallel_for,
2042 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2043 OMPLoopScope PreInitScope(CGF, S);
2044 CGF.EmitStmt(
2045 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2046 });
2047}
2048
Kelvin Li83c451e2016-12-25 04:52:54 +00002049void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2050 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002051 CGM.getOpenMPRuntime().emitInlinedDirective(
2052 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002053 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002054 CGF.EmitStmt(
2055 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002056 });
2057}
2058
Kelvin Li80e8f562016-12-29 22:16:30 +00002059void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2060 const OMPTargetTeamsDistributeParallelForDirective &S) {
2061 CGM.getOpenMPRuntime().emitInlinedDirective(
2062 *this, OMPD_target_teams_distribute_parallel_for,
2063 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2064 CGF.EmitStmt(
2065 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2066 });
2067}
2068
Kelvin Li1851df52017-01-03 05:23:48 +00002069void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2070 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2071 CGM.getOpenMPRuntime().emitInlinedDirective(
2072 *this, OMPD_target_teams_distribute_parallel_for_simd,
2073 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2074 CGF.EmitStmt(
2075 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2076 });
2077}
2078
Kelvin Lida681182017-01-10 18:08:18 +00002079void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2080 const OMPTargetTeamsDistributeSimdDirective &S) {
2081 CGM.getOpenMPRuntime().emitInlinedDirective(
2082 *this, OMPD_target_teams_distribute_simd,
2083 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2084 CGF.EmitStmt(
2085 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2086 });
2087}
2088
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002089namespace {
2090 struct ScheduleKindModifiersTy {
2091 OpenMPScheduleClauseKind Kind;
2092 OpenMPScheduleClauseModifier M1;
2093 OpenMPScheduleClauseModifier M2;
2094 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2095 OpenMPScheduleClauseModifier M1,
2096 OpenMPScheduleClauseModifier M2)
2097 : Kind(Kind), M1(M1), M2(M2) {}
2098 };
2099} // namespace
2100
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002101bool CodeGenFunction::EmitOMPWorksharingLoop(
2102 const OMPLoopDirective &S, Expr *EUB,
2103 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2104 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002105 // Emit the loop iteration variable.
2106 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2107 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2108 EmitVarDecl(*IVDecl);
2109
2110 // Emit the iterations count variable.
2111 // If it is not a variable, Sema decided to calculate iterations count on each
2112 // iteration (e.g., it is foldable into a constant).
2113 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2114 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2115 // Emit calculation of the iterations count.
2116 EmitIgnoredExpr(S.getCalcLastIteration());
2117 }
2118
2119 auto &RT = CGM.getOpenMPRuntime();
2120
Alexey Bataev38e89532015-04-16 04:54:05 +00002121 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002122 // Check pre-condition.
2123 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002124 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002125 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002126 // If the condition constant folds and can be elided, avoid emitting the
2127 // whole loop.
2128 bool CondConstant;
2129 llvm::BasicBlock *ContBlock = nullptr;
2130 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2131 if (!CondConstant)
2132 return false;
2133 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002134 auto *ThenBlock = createBasicBlock("omp.precond.then");
2135 ContBlock = createBasicBlock("omp.precond.end");
2136 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002137 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002138 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002139 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002140 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002141
Alexey Bataev8b427062016-05-25 12:36:08 +00002142 bool Ordered = false;
2143 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2144 if (OrderedClause->getNumForLoops())
2145 RT.emitDoacrossInit(*this, S);
2146 else
2147 Ordered = true;
2148 }
2149
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002150 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002151 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002152 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002153 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002154
2155 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2156 LValue LB = Bounds.first;
2157 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002158 LValue ST =
2159 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2160 LValue IL =
2161 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2162
Alexander Musmanc6388682014-12-15 07:07:06 +00002163 // Emit 'then' code.
2164 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002165 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002166 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2167 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002168 // initialization of firstprivate variables and post-update of
2169 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002170 CGM.getOpenMPRuntime().emitBarrierCall(
2171 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2172 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002173 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002174 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002175 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002176 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002177 EmitOMPPrivateLoopCounters(S, LoopScope);
2178 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002179 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002180
2181 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002182 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002183 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002184 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002185 ScheduleKind.Schedule = C->getScheduleKind();
2186 ScheduleKind.M1 = C->getFirstScheduleModifier();
2187 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002188 if (const auto *Ch = C->getChunkSize()) {
2189 Chunk = EmitScalarExpr(Ch);
2190 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2191 S.getIterationVariable()->getType(),
2192 S.getLocStart());
2193 }
2194 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2196 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002197 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2198 // If the static schedule kind is specified or if the ordered clause is
2199 // specified, and if no monotonic modifier is specified, the effect will
2200 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002201 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002202 /* Chunked */ Chunk != nullptr) &&
2203 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002204 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2205 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002206 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2207 // When no chunk_size is specified, the iteration space is divided into
2208 // chunks that are approximately equal in size, and at most one chunk is
2209 // distributed to each thread. Note that the size of the chunks is
2210 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002211 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2212 IVSize, IVSigned, Ordered,
2213 IL.getAddress(), LB.getAddress(),
2214 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002215 auto LoopExit =
2216 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002217 // UB = min(UB, GlobalUB);
2218 EmitIgnoredExpr(S.getEnsureUpperBound());
2219 // IV = LB;
2220 EmitIgnoredExpr(S.getInit());
2221 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002222 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2223 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002224 [&S, LoopExit](CodeGenFunction &CGF) {
2225 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002226 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002227 },
2228 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002229 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002230 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002231 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2232 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2233 };
2234 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002235 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002236 const bool IsMonotonic =
2237 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2238 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2239 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2240 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002241 // Emit the outer loop, which requests its work chunk [LB..UB] from
2242 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002243 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2244 ST.getAddress(), IL.getAddress(),
2245 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002246 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002247 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002248 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002249 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2250 EmitOMPSimdFinal(S,
2251 [&](CodeGenFunction &CGF) -> llvm::Value * {
2252 return CGF.Builder.CreateIsNotNull(
2253 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2254 });
2255 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002256 EmitOMPReductionClauseFinal(
2257 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2258 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2259 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002260 // Emit post-update of the reduction variables if IsLastIter != 0.
2261 emitPostUpdateForReductionClause(
2262 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2263 return CGF.Builder.CreateIsNotNull(
2264 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2265 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002266 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2267 if (HasLastprivateClause)
2268 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002269 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2270 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002271 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002272 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002273 return CGF.Builder.CreateIsNotNull(
2274 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2275 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002276 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002277 if (ContBlock) {
2278 EmitBranch(ContBlock);
2279 EmitBlock(ContBlock, true);
2280 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002281 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002282 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002283}
2284
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002285/// The following two functions generate expressions for the loop lower
2286/// and upper bounds in case of static and dynamic (dispatch) schedule
2287/// of the associated 'for' or 'distribute' loop.
2288static std::pair<LValue, LValue>
2289emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2290 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2291 LValue LB =
2292 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2293 LValue UB =
2294 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2295 return {LB, UB};
2296}
2297
2298/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2299/// consider the lower and upper bound expressions generated by the
2300/// worksharing loop support, but we use 0 and the iteration space size as
2301/// constants
2302static std::pair<llvm::Value *, llvm::Value *>
2303emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2304 Address LB, Address UB) {
2305 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2306 const Expr *IVExpr = LS.getIterationVariable();
2307 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2308 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2309 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2310 return {LBVal, UBVal};
2311}
2312
Alexander Musmanc6388682014-12-15 07:07:06 +00002313void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002314 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002315 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2316 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002317 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002318 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2319 emitForLoopBounds,
2320 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002321 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002322 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002323 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002324 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2325 S.hasCancel());
2326 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002327
2328 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002329 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002330 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2331 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002332}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002333
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002334void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002335 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002336 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2337 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002338 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2339 emitForLoopBounds,
2340 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002341 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002342 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002343 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002344 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2345 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002346
2347 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002348 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002349 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2350 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002351}
2352
Alexey Bataev2df54a02015-03-12 08:53:29 +00002353static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2354 const Twine &Name,
2355 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002356 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002357 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002358 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002359 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002360}
2361
Alexey Bataev3392d762016-02-16 11:18:12 +00002362void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002363 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2364 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002365 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002366 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2367 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002368 auto &C = CGF.CGM.getContext();
2369 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2370 // Emit helper vars inits.
2371 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2372 CGF.Builder.getInt32(0));
2373 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2374 : CGF.Builder.getInt32(0);
2375 LValue UB =
2376 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2377 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2378 CGF.Builder.getInt32(1));
2379 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2380 CGF.Builder.getInt32(0));
2381 // Loop counter.
2382 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2383 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2384 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2385 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2386 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2387 // Generate condition for loop.
2388 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002389 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002390 // Increment for loop counter.
2391 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2392 S.getLocStart());
2393 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2394 // Iterate through all sections and emit a switch construct:
2395 // switch (IV) {
2396 // case 0:
2397 // <SectionStmt[0]>;
2398 // break;
2399 // ...
2400 // case <NumSection> - 1:
2401 // <SectionStmt[<NumSection> - 1]>;
2402 // break;
2403 // }
2404 // .omp.sections.exit:
2405 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2406 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2407 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2408 CS == nullptr ? 1 : CS->size());
2409 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002410 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002411 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002412 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2413 CGF.EmitBlock(CaseBB);
2414 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002415 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002416 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002417 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002418 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002419 } else {
2420 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2421 CGF.EmitBlock(CaseBB);
2422 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2423 CGF.EmitStmt(Stmt);
2424 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002425 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002426 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002427 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002428
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002429 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2430 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002431 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002432 // initialization of firstprivate variables and post-update of lastprivate
2433 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002434 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2435 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2436 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002437 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002438 CGF.EmitOMPPrivateClause(S, LoopScope);
2439 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2440 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2441 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002442
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002443 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002444 OpenMPScheduleTy ScheduleKind;
2445 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002446 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002447 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002448 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2449 UB.getAddress(), ST.getAddress());
2450 // UB = min(UB, GlobalUB);
2451 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2452 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2453 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2454 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2455 // IV = LB;
2456 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2457 // while (idx <= UB) { BODY; ++idx; }
2458 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2459 [](CodeGenFunction &) {});
2460 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002461 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2462 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2463 };
2464 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002465 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002466 // Emit post-update of the reduction variables if IsLastIter != 0.
2467 emitPostUpdateForReductionClause(
2468 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2469 return CGF.Builder.CreateIsNotNull(
2470 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2471 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002472
2473 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2474 if (HasLastprivates)
2475 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002476 S, /*NoFinals=*/false,
2477 CGF.Builder.CreateIsNotNull(
2478 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002479 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002480
2481 bool HasCancel = false;
2482 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2483 HasCancel = OSD->hasCancel();
2484 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2485 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002486 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002487 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2488 HasCancel);
2489 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2490 // clause. Otherwise the barrier will be generated by the codegen for the
2491 // directive.
2492 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002493 // Emit implicit barrier to synchronize threads and avoid data races on
2494 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002495 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2496 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002497 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002498}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002499
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002500void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002501 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002502 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002503 EmitSections(S);
2504 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002505 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002506 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002507 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2508 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002509 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002510}
2511
2512void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002513 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002514 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002515 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002516 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002517 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2518 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002519}
2520
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002521void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002522 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002523 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002524 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002525 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002526 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002527 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002528 // Build a list of copyprivate variables along with helper expressions
2529 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002530 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002531 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002532 DestExprs.append(C->destination_exprs().begin(),
2533 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002534 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002535 AssignmentOps.append(C->assignment_ops().begin(),
2536 C->assignment_ops().end());
2537 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002538 // Emit code for 'single' region along with 'copyprivate' clauses
2539 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2540 Action.Enter(CGF);
2541 OMPPrivateScope SingleScope(CGF);
2542 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2543 CGF.EmitOMPPrivateClause(S, SingleScope);
2544 (void)SingleScope.Privatize();
2545 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2546 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002547 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002548 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002549 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2550 CopyprivateVars, DestExprs,
2551 SrcExprs, AssignmentOps);
2552 }
2553 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2554 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002555 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002556 CGM.getOpenMPRuntime().emitBarrierCall(
2557 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002558 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002559 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002560}
2561
Alexey Bataev8d690652014-12-04 07:23:53 +00002562void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002563 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2564 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002565 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002566 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002567 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002568 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002569}
2570
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002571void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002572 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2573 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002574 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002575 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002576 Expr *Hint = nullptr;
2577 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2578 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002579 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002580 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2581 S.getDirectiveName().getAsString(),
2582 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002583}
2584
Alexey Bataev671605e2015-04-13 05:28:11 +00002585void CodeGenFunction::EmitOMPParallelForDirective(
2586 const OMPParallelForDirective &S) {
2587 // Emit directive as a combined directive that consists of two implicit
2588 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002589 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002590 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002591 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2592 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002593 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002594 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2595 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002596}
2597
Alexander Musmane4e893b2014-09-23 09:33:00 +00002598void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002599 const OMPParallelForSimdDirective &S) {
2600 // Emit directive as a combined directive that consists of two implicit
2601 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002603 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2604 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002605 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002606 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2607 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002608}
2609
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002610void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002611 const OMPParallelSectionsDirective &S) {
2612 // Emit directive as a combined directive that consists of two implicit
2613 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002614 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2615 CGF.EmitSections(S);
2616 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002617 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2618 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002619}
2620
Alexey Bataev7292c292016-04-25 12:22:29 +00002621void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2622 const RegionCodeGenTy &BodyGen,
2623 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002624 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002625 // Emit outlined function for task construct.
2626 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002627 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002628 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002629 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002630 // Check if the task is final
2631 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2632 // If the condition constant folds and can be elided, try to avoid emitting
2633 // the condition and the dead arm of the if/else.
2634 auto *Cond = Clause->getCondition();
2635 bool CondConstant;
2636 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2637 Data.Final.setInt(CondConstant);
2638 else
2639 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2640 } else {
2641 // By default the task is not final.
2642 Data.Final.setInt(/*IntVal=*/false);
2643 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002644 // Check if the task has 'priority' clause.
2645 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002646 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002647 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002648 Data.Priority.setPointer(EmitScalarConversion(
2649 EmitScalarExpr(Prio), Prio->getType(),
2650 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2651 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002652 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002653 // The first function argument for tasks is a thread id, the second one is a
2654 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002655 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2656 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002657 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002658 auto IRef = C->varlist_begin();
2659 for (auto *IInit : C->private_copies()) {
2660 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2661 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002662 Data.PrivateVars.push_back(*IRef);
2663 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002664 }
2665 ++IRef;
2666 }
2667 }
2668 EmittedAsPrivate.clear();
2669 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002670 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002671 auto IRef = C->varlist_begin();
2672 auto IElemInitRef = C->inits().begin();
2673 for (auto *IInit : C->private_copies()) {
2674 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2675 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002676 Data.FirstprivateVars.push_back(*IRef);
2677 Data.FirstprivateCopies.push_back(IInit);
2678 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002679 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002680 ++IRef;
2681 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002682 }
2683 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002684 // Get list of lastprivate variables (for taskloops).
2685 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2686 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2687 auto IRef = C->varlist_begin();
2688 auto ID = C->destination_exprs().begin();
2689 for (auto *IInit : C->private_copies()) {
2690 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2691 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2692 Data.LastprivateVars.push_back(*IRef);
2693 Data.LastprivateCopies.push_back(IInit);
2694 }
2695 LastprivateDstsOrigs.insert(
2696 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2697 cast<DeclRefExpr>(*IRef)});
2698 ++IRef;
2699 ++ID;
2700 }
2701 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002702 SmallVector<const Expr *, 4> LHSs;
2703 SmallVector<const Expr *, 4> RHSs;
2704 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2705 auto IPriv = C->privates().begin();
2706 auto IRed = C->reduction_ops().begin();
2707 auto ILHS = C->lhs_exprs().begin();
2708 auto IRHS = C->rhs_exprs().begin();
2709 for (const auto *Ref : C->varlists()) {
2710 Data.ReductionVars.emplace_back(Ref);
2711 Data.ReductionCopies.emplace_back(*IPriv);
2712 Data.ReductionOps.emplace_back(*IRed);
2713 LHSs.emplace_back(*ILHS);
2714 RHSs.emplace_back(*IRHS);
2715 std::advance(IPriv, 1);
2716 std::advance(IRed, 1);
2717 std::advance(ILHS, 1);
2718 std::advance(IRHS, 1);
2719 }
2720 }
2721 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2722 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002723 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002724 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2725 for (auto *IRef : C->varlists())
2726 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002727 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002728 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002729 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002730 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002731 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2732 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002733 auto *CopyFn = CGF.Builder.CreateLoad(
2734 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2735 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2736 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2737 // Map privates.
2738 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2739 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2740 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002741 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002742 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2743 Address PrivatePtr = CGF.CreateMemTemp(
2744 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2745 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2746 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002747 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002748 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002749 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2750 Address PrivatePtr =
2751 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2752 ".firstpriv.ptr.addr");
2753 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2754 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002755 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002756 for (auto *E : Data.LastprivateVars) {
2757 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2758 Address PrivatePtr =
2759 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2760 ".lastpriv.ptr.addr");
2761 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2762 CallArgs.push_back(PrivatePtr.getPointer());
2763 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002764 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002765 for (auto &&Pair : LastprivateDstsOrigs) {
2766 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2767 DeclRefExpr DRE(
2768 const_cast<VarDecl *>(OrigVD),
2769 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2770 OrigVD) != nullptr,
2771 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2772 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2773 return CGF.EmitLValue(&DRE).getAddress();
2774 });
2775 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002776 for (auto &&Pair : PrivatePtrs) {
2777 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2778 CGF.getContext().getDeclAlign(Pair.first));
2779 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2780 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002781 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002782 if (Data.Reductions) {
2783 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2784 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2785 Data.ReductionOps);
2786 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2787 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2788 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2789 RedCG.emitSharedLValue(CGF, Cnt);
2790 RedCG.emitAggregateType(CGF, Cnt);
2791 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2792 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2793 Replacement =
2794 Address(CGF.EmitScalarConversion(
2795 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2796 CGF.getContext().getPointerType(
2797 Data.ReductionCopies[Cnt]->getType()),
2798 SourceLocation()),
2799 Replacement.getAlignment());
2800 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2801 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2802 [Replacement]() { return Replacement; });
2803 // FIXME: This must removed once the runtime library is fixed.
2804 // Emit required threadprivate variables for
2805 // initilizer/combiner/finalizer.
2806 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2807 RedCG, Cnt);
2808 }
2809 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002810 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002811 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002812 SmallVector<const Expr *, 4> InRedVars;
2813 SmallVector<const Expr *, 4> InRedPrivs;
2814 SmallVector<const Expr *, 4> InRedOps;
2815 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2816 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2817 auto IPriv = C->privates().begin();
2818 auto IRed = C->reduction_ops().begin();
2819 auto ITD = C->taskgroup_descriptors().begin();
2820 for (const auto *Ref : C->varlists()) {
2821 InRedVars.emplace_back(Ref);
2822 InRedPrivs.emplace_back(*IPriv);
2823 InRedOps.emplace_back(*IRed);
2824 TaskgroupDescriptors.emplace_back(*ITD);
2825 std::advance(IPriv, 1);
2826 std::advance(IRed, 1);
2827 std::advance(ITD, 1);
2828 }
2829 }
2830 // Privatize in_reduction items here, because taskgroup descriptors must be
2831 // privatized earlier.
2832 OMPPrivateScope InRedScope(CGF);
2833 if (!InRedVars.empty()) {
2834 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2835 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2836 RedCG.emitSharedLValue(CGF, Cnt);
2837 RedCG.emitAggregateType(CGF, Cnt);
2838 // The taskgroup descriptor variable is always implicit firstprivate and
2839 // privatized already during procoessing of the firstprivates.
2840 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2841 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2842 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2843 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2844 Replacement = Address(
2845 CGF.EmitScalarConversion(
2846 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2847 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2848 SourceLocation()),
2849 Replacement.getAlignment());
2850 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2851 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2852 [Replacement]() { return Replacement; });
2853 // FIXME: This must removed once the runtime library is fixed.
2854 // Emit required threadprivate variables for
2855 // initilizer/combiner/finalizer.
2856 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2857 RedCG, Cnt);
2858 }
2859 }
2860 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002861
2862 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002863 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002864 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002865 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2866 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2867 Data.NumberOfParts);
2868 OMPLexicalScope Scope(*this, S);
2869 TaskGen(*this, OutlinedFn, Data);
2870}
2871
2872void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2873 // Emit outlined function for task construct.
2874 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2875 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002876 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002877 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002878 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2879 if (C->getNameModifier() == OMPD_unknown ||
2880 C->getNameModifier() == OMPD_task) {
2881 IfCond = C->getCondition();
2882 break;
2883 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002884 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002885
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002886 OMPTaskDataTy Data;
2887 // Check if we should emit tied or untied task.
2888 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002889 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2890 CGF.EmitStmt(CS->getCapturedStmt());
2891 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002892 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002893 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002894 const OMPTaskDataTy &Data) {
2895 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2896 SharedsTy, CapturedStruct, IfCond,
2897 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002898 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002899 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002900}
2901
Alexey Bataev9f797f32015-02-05 05:57:51 +00002902void CodeGenFunction::EmitOMPTaskyieldDirective(
2903 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002904 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002905}
2906
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002907void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002908 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002909}
2910
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002911void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2912 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002913}
2914
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002915void CodeGenFunction::EmitOMPTaskgroupDirective(
2916 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002917 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2918 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002919 if (const Expr *E = S.getReductionRef()) {
2920 SmallVector<const Expr *, 4> LHSs;
2921 SmallVector<const Expr *, 4> RHSs;
2922 OMPTaskDataTy Data;
2923 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2924 auto IPriv = C->privates().begin();
2925 auto IRed = C->reduction_ops().begin();
2926 auto ILHS = C->lhs_exprs().begin();
2927 auto IRHS = C->rhs_exprs().begin();
2928 for (const auto *Ref : C->varlists()) {
2929 Data.ReductionVars.emplace_back(Ref);
2930 Data.ReductionCopies.emplace_back(*IPriv);
2931 Data.ReductionOps.emplace_back(*IRed);
2932 LHSs.emplace_back(*ILHS);
2933 RHSs.emplace_back(*IRHS);
2934 std::advance(IPriv, 1);
2935 std::advance(IRed, 1);
2936 std::advance(ILHS, 1);
2937 std::advance(IRHS, 1);
2938 }
2939 }
2940 llvm::Value *ReductionDesc =
2941 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2942 LHSs, RHSs, Data);
2943 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2944 CGF.EmitVarDecl(*VD);
2945 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2946 /*Volatile=*/false, E->getType());
2947 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002948 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002949 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002950 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002951 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2952}
2953
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002954void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002955 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002956 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002957 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2958 FlushClause->varlist_end());
2959 }
2960 return llvm::None;
2961 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002962}
2963
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002964void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
2965 const CodeGenLoopTy &CodeGenLoop,
2966 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002967 // Emit the loop iteration variable.
2968 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2969 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2970 EmitVarDecl(*IVDecl);
2971
2972 // Emit the iterations count variable.
2973 // If it is not a variable, Sema decided to calculate iterations count on each
2974 // iteration (e.g., it is foldable into a constant).
2975 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2976 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2977 // Emit calculation of the iterations count.
2978 EmitIgnoredExpr(S.getCalcLastIteration());
2979 }
2980
2981 auto &RT = CGM.getOpenMPRuntime();
2982
Carlo Bertolli962bb802017-01-03 18:24:42 +00002983 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002984 // Check pre-condition.
2985 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002986 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002987 // Skip the entire loop if we don't meet the precondition.
2988 // If the condition constant folds and can be elided, avoid emitting the
2989 // whole loop.
2990 bool CondConstant;
2991 llvm::BasicBlock *ContBlock = nullptr;
2992 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2993 if (!CondConstant)
2994 return;
2995 } else {
2996 auto *ThenBlock = createBasicBlock("omp.precond.then");
2997 ContBlock = createBasicBlock("omp.precond.end");
2998 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2999 getProfileCount(&S));
3000 EmitBlock(ThenBlock);
3001 incrementProfileCounter(&S);
3002 }
3003
3004 // Emit 'then' code.
3005 {
3006 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003007
3008 LValue LB = EmitOMPHelperVar(
3009 *this, cast<DeclRefExpr>(
3010 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3011 ? S.getCombinedLowerBoundVariable()
3012 : S.getLowerBoundVariable())));
3013 LValue UB = EmitOMPHelperVar(
3014 *this, cast<DeclRefExpr>(
3015 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3016 ? S.getCombinedUpperBoundVariable()
3017 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003018 LValue ST =
3019 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3020 LValue IL =
3021 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3022
3023 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003024 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3025 // Emit implicit barrier to synchronize threads and avoid data races on
3026 // initialization of firstprivate variables and post-update of
3027 // lastprivate variables.
3028 CGM.getOpenMPRuntime().emitBarrierCall(
3029 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3030 /*ForceSimpleCall=*/true);
3031 }
3032 EmitOMPPrivateClause(S, LoopScope);
3033 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003034 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003035 (void)LoopScope.Privatize();
3036
3037 // Detect the distribute schedule kind and chunk.
3038 llvm::Value *Chunk = nullptr;
3039 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3040 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3041 ScheduleKind = C->getDistScheduleKind();
3042 if (const auto *Ch = C->getChunkSize()) {
3043 Chunk = EmitScalarExpr(Ch);
3044 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3045 S.getIterationVariable()->getType(),
3046 S.getLocStart());
3047 }
3048 }
3049 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3050 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3051
3052 // OpenMP [2.10.8, distribute Construct, Description]
3053 // If dist_schedule is specified, kind must be static. If specified,
3054 // iterations are divided into chunks of size chunk_size, chunks are
3055 // assigned to the teams of the league in a round-robin fashion in the
3056 // order of the team number. When no chunk_size is specified, the
3057 // iteration space is divided into chunks that are approximately equal
3058 // in size, and at most one chunk is distributed to each team of the
3059 // league. The size of the chunks is unspecified in this case.
3060 if (RT.isStaticNonchunked(ScheduleKind,
3061 /* Chunked */ Chunk != nullptr)) {
3062 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
3063 IVSize, IVSigned, /* Ordered = */ false,
3064 IL.getAddress(), LB.getAddress(),
3065 UB.getAddress(), ST.getAddress());
3066 auto LoopExit =
3067 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3068 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003069 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3070 ? S.getCombinedEnsureUpperBound()
3071 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003072 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003073 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3074 ? S.getCombinedInit()
3075 : S.getInit());
3076
3077 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3078 ? S.getCombinedCond()
3079 : S.getCond();
3080
3081 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003082 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003083 // when combined with 'for' (e.g. as in 'distribute parallel for')
3084 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3085 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3086 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3087 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003088 },
3089 [](CodeGenFunction &) {});
3090 EmitBlock(LoopExit.getBlock());
3091 // Tell the runtime we are done.
3092 RT.emitForStaticFinish(*this, S.getLocStart());
3093 } else {
3094 // Emit the outer loop, which requests its work chunk [LB..UB] from
3095 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003096 const OMPLoopArguments LoopArguments = {
3097 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3098 Chunk};
3099 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3100 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003101 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003102
3103 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3104 if (HasLastprivateClause)
3105 EmitOMPLastprivateClauseFinal(
3106 S, /*NoFinals=*/false,
3107 Builder.CreateIsNotNull(
3108 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003109 }
3110
3111 // We're now done with the loop, so jump to the continuation block.
3112 if (ContBlock) {
3113 EmitBranch(ContBlock);
3114 EmitBlock(ContBlock, true);
3115 }
3116 }
3117}
3118
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003119void CodeGenFunction::EmitOMPDistributeDirective(
3120 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003121 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003122
3123 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003124 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003125 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003126 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3127 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003128}
3129
Alexey Bataev5f600d62015-09-29 03:48:57 +00003130static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3131 const CapturedStmt *S) {
3132 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3133 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3134 CGF.CapturedStmtInfo = &CapStmtInfo;
3135 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3136 Fn->addFnAttr(llvm::Attribute::NoInline);
3137 return Fn;
3138}
3139
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003140void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003141 if (!S.getAssociatedStmt()) {
3142 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3143 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003144 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003145 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003146 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003147 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3148 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003149 if (C) {
3150 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3151 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3152 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3153 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00003154 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, OutlinedFn,
3155 CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003156 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003157 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003158 CGF.EmitStmt(
3159 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3160 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003161 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003162 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003163 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003164}
3165
Alexey Bataevb57056f2015-01-22 06:17:56 +00003166static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003167 QualType SrcType, QualType DestType,
3168 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003169 assert(CGF.hasScalarEvaluationKind(DestType) &&
3170 "DestType must have scalar evaluation kind.");
3171 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3172 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003173 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3174 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003175 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003176 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003177}
3178
3179static CodeGenFunction::ComplexPairTy
3180convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003181 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003182 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3183 "DestType must have complex evaluation kind.");
3184 CodeGenFunction::ComplexPairTy ComplexVal;
3185 if (Val.isScalar()) {
3186 // Convert the input element to the element type of the complex.
3187 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003188 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3189 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003190 ComplexVal = CodeGenFunction::ComplexPairTy(
3191 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3192 } else {
3193 assert(Val.isComplex() && "Must be a scalar or complex.");
3194 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3195 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3196 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003197 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003198 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003199 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003200 }
3201 return ComplexVal;
3202}
3203
Alexey Bataev5e018f92015-04-23 06:35:10 +00003204static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3205 LValue LVal, RValue RVal) {
3206 if (LVal.isGlobalReg()) {
3207 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3208 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003209 CGF.EmitAtomicStore(RVal, LVal,
3210 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3211 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003212 LVal.isVolatile(), /*IsInit=*/false);
3213 }
3214}
3215
Alexey Bataev8524d152016-01-21 12:35:58 +00003216void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3217 QualType RValTy, SourceLocation Loc) {
3218 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003219 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003220 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3221 *this, RVal, RValTy, LVal.getType(), Loc)),
3222 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003223 break;
3224 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003225 EmitStoreOfComplex(
3226 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003227 /*isInit=*/false);
3228 break;
3229 case TEK_Aggregate:
3230 llvm_unreachable("Must be a scalar or complex.");
3231 }
3232}
3233
Alexey Bataevb57056f2015-01-22 06:17:56 +00003234static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3235 const Expr *X, const Expr *V,
3236 SourceLocation Loc) {
3237 // v = x;
3238 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3239 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3240 LValue XLValue = CGF.EmitLValue(X);
3241 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003242 RValue Res = XLValue.isGlobalReg()
3243 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003244 : CGF.EmitAtomicLoad(
3245 XLValue, Loc,
3246 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3247 : llvm::AtomicOrdering::Monotonic,
3248 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003249 // OpenMP, 2.12.6, atomic Construct
3250 // Any atomic construct with a seq_cst clause forces the atomically
3251 // performed operation to include an implicit flush operation without a
3252 // list.
3253 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003254 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003255 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003256}
3257
Alexey Bataevb8329262015-02-27 06:33:30 +00003258static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3259 const Expr *X, const Expr *E,
3260 SourceLocation Loc) {
3261 // x = expr;
3262 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003263 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003264 // OpenMP, 2.12.6, atomic Construct
3265 // Any atomic construct with a seq_cst clause forces the atomically
3266 // performed operation to include an implicit flush operation without a
3267 // list.
3268 if (IsSeqCst)
3269 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3270}
3271
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003272static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3273 RValue Update,
3274 BinaryOperatorKind BO,
3275 llvm::AtomicOrdering AO,
3276 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003277 auto &Context = CGF.CGM.getContext();
3278 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003279 // expression is simple and atomic is allowed for the given type for the
3280 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003281 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003282 !Update.getScalarVal()->getType()->isIntegerTy() ||
3283 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3284 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003285 X.getAddress().getElementType())) ||
3286 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003287 !Context.getTargetInfo().hasBuiltinAtomic(
3288 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003289 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003290
3291 llvm::AtomicRMWInst::BinOp RMWOp;
3292 switch (BO) {
3293 case BO_Add:
3294 RMWOp = llvm::AtomicRMWInst::Add;
3295 break;
3296 case BO_Sub:
3297 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003298 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003299 RMWOp = llvm::AtomicRMWInst::Sub;
3300 break;
3301 case BO_And:
3302 RMWOp = llvm::AtomicRMWInst::And;
3303 break;
3304 case BO_Or:
3305 RMWOp = llvm::AtomicRMWInst::Or;
3306 break;
3307 case BO_Xor:
3308 RMWOp = llvm::AtomicRMWInst::Xor;
3309 break;
3310 case BO_LT:
3311 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3312 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3313 : llvm::AtomicRMWInst::Max)
3314 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3315 : llvm::AtomicRMWInst::UMax);
3316 break;
3317 case BO_GT:
3318 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3319 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3320 : llvm::AtomicRMWInst::Min)
3321 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3322 : llvm::AtomicRMWInst::UMin);
3323 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003324 case BO_Assign:
3325 RMWOp = llvm::AtomicRMWInst::Xchg;
3326 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003327 case BO_Mul:
3328 case BO_Div:
3329 case BO_Rem:
3330 case BO_Shl:
3331 case BO_Shr:
3332 case BO_LAnd:
3333 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003334 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003335 case BO_PtrMemD:
3336 case BO_PtrMemI:
3337 case BO_LE:
3338 case BO_GE:
3339 case BO_EQ:
3340 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003341 case BO_AddAssign:
3342 case BO_SubAssign:
3343 case BO_AndAssign:
3344 case BO_OrAssign:
3345 case BO_XorAssign:
3346 case BO_MulAssign:
3347 case BO_DivAssign:
3348 case BO_RemAssign:
3349 case BO_ShlAssign:
3350 case BO_ShrAssign:
3351 case BO_Comma:
3352 llvm_unreachable("Unsupported atomic update operation");
3353 }
3354 auto *UpdateVal = Update.getScalarVal();
3355 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3356 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003357 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003358 X.getType()->hasSignedIntegerRepresentation());
3359 }
John McCall7f416cc2015-09-08 08:05:57 +00003360 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003361 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003362}
3363
Alexey Bataev5e018f92015-04-23 06:35:10 +00003364std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003365 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3366 llvm::AtomicOrdering AO, SourceLocation Loc,
3367 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3368 // Update expressions are allowed to have the following forms:
3369 // x binop= expr; -> xrval + expr;
3370 // x++, ++x -> xrval + 1;
3371 // x--, --x -> xrval - 1;
3372 // x = x binop expr; -> xrval binop expr
3373 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003374 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3375 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003376 if (X.isGlobalReg()) {
3377 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3378 // 'xrval'.
3379 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3380 } else {
3381 // Perform compare-and-swap procedure.
3382 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003383 }
3384 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003385 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003386}
3387
3388static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3389 const Expr *X, const Expr *E,
3390 const Expr *UE, bool IsXLHSInRHSPart,
3391 SourceLocation Loc) {
3392 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3393 "Update expr in 'atomic update' must be a binary operator.");
3394 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3395 // Update expressions are allowed to have the following forms:
3396 // x binop= expr; -> xrval + expr;
3397 // x++, ++x -> xrval + 1;
3398 // x--, --x -> xrval - 1;
3399 // x = x binop expr; -> xrval binop expr
3400 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003401 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003402 LValue XLValue = CGF.EmitLValue(X);
3403 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003404 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3405 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003406 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3407 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3408 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3409 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3410 auto Gen =
3411 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3412 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3413 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3414 return CGF.EmitAnyExpr(UE);
3415 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003416 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3417 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3418 // OpenMP, 2.12.6, atomic Construct
3419 // Any atomic construct with a seq_cst clause forces the atomically
3420 // performed operation to include an implicit flush operation without a
3421 // list.
3422 if (IsSeqCst)
3423 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3424}
3425
3426static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003427 QualType SourceType, QualType ResType,
3428 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003429 switch (CGF.getEvaluationKind(ResType)) {
3430 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003431 return RValue::get(
3432 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003433 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003434 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003435 return RValue::getComplex(Res.first, Res.second);
3436 }
3437 case TEK_Aggregate:
3438 break;
3439 }
3440 llvm_unreachable("Must be a scalar or complex.");
3441}
3442
3443static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3444 bool IsPostfixUpdate, const Expr *V,
3445 const Expr *X, const Expr *E,
3446 const Expr *UE, bool IsXLHSInRHSPart,
3447 SourceLocation Loc) {
3448 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3449 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3450 RValue NewVVal;
3451 LValue VLValue = CGF.EmitLValue(V);
3452 LValue XLValue = CGF.EmitLValue(X);
3453 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003454 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3455 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003456 QualType NewVValType;
3457 if (UE) {
3458 // 'x' is updated with some additional value.
3459 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3460 "Update expr in 'atomic capture' must be a binary operator.");
3461 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3462 // Update expressions are allowed to have the following forms:
3463 // x binop= expr; -> xrval + expr;
3464 // x++, ++x -> xrval + 1;
3465 // x--, --x -> xrval - 1;
3466 // x = x binop expr; -> xrval binop expr
3467 // x = expr Op x; - > expr binop xrval;
3468 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3469 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3470 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3471 NewVValType = XRValExpr->getType();
3472 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3473 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003474 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003475 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3476 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3477 RValue Res = CGF.EmitAnyExpr(UE);
3478 NewVVal = IsPostfixUpdate ? XRValue : Res;
3479 return Res;
3480 };
3481 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3482 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3483 if (Res.first) {
3484 // 'atomicrmw' instruction was generated.
3485 if (IsPostfixUpdate) {
3486 // Use old value from 'atomicrmw'.
3487 NewVVal = Res.second;
3488 } else {
3489 // 'atomicrmw' does not provide new value, so evaluate it using old
3490 // value of 'x'.
3491 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3492 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3493 NewVVal = CGF.EmitAnyExpr(UE);
3494 }
3495 }
3496 } else {
3497 // 'x' is simply rewritten with some 'expr'.
3498 NewVValType = X->getType().getNonReferenceType();
3499 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003500 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003501 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003502 NewVVal = XRValue;
3503 return ExprRValue;
3504 };
3505 // Try to perform atomicrmw xchg, otherwise simple exchange.
3506 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3507 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3508 Loc, Gen);
3509 if (Res.first) {
3510 // 'atomicrmw' instruction was generated.
3511 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3512 }
3513 }
3514 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003515 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003516 // OpenMP, 2.12.6, atomic Construct
3517 // Any atomic construct with a seq_cst clause forces the atomically
3518 // performed operation to include an implicit flush operation without a
3519 // list.
3520 if (IsSeqCst)
3521 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3522}
3523
Alexey Bataevb57056f2015-01-22 06:17:56 +00003524static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003525 bool IsSeqCst, bool IsPostfixUpdate,
3526 const Expr *X, const Expr *V, const Expr *E,
3527 const Expr *UE, bool IsXLHSInRHSPart,
3528 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003529 switch (Kind) {
3530 case OMPC_read:
3531 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3532 break;
3533 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003534 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3535 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003536 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003537 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003538 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3539 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003540 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003541 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3542 IsXLHSInRHSPart, Loc);
3543 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003544 case OMPC_if:
3545 case OMPC_final:
3546 case OMPC_num_threads:
3547 case OMPC_private:
3548 case OMPC_firstprivate:
3549 case OMPC_lastprivate:
3550 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003551 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003552 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003553 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003554 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003555 case OMPC_collapse:
3556 case OMPC_default:
3557 case OMPC_seq_cst:
3558 case OMPC_shared:
3559 case OMPC_linear:
3560 case OMPC_aligned:
3561 case OMPC_copyin:
3562 case OMPC_copyprivate:
3563 case OMPC_flush:
3564 case OMPC_proc_bind:
3565 case OMPC_schedule:
3566 case OMPC_ordered:
3567 case OMPC_nowait:
3568 case OMPC_untied:
3569 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003570 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003571 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003572 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003573 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003574 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003575 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003576 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003577 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003578 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003579 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003580 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003581 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003582 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003583 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003584 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003585 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003586 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003587 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003588 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003589 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003590 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3591 }
3592}
3593
3594void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003595 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003596 OpenMPClauseKind Kind = OMPC_unknown;
3597 for (auto *C : S.clauses()) {
3598 // Find first clause (skip seq_cst clause, if it is first).
3599 if (C->getClauseKind() != OMPC_seq_cst) {
3600 Kind = C->getClauseKind();
3601 break;
3602 }
3603 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003604
3605 const auto *CS =
3606 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003607 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003608 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003609 }
3610 // Processing for statements under 'atomic capture'.
3611 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3612 for (const auto *C : Compound->body()) {
3613 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3614 enterFullExpression(EWC);
3615 }
3616 }
3617 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003618
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003619 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3620 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003621 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003622 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3623 S.getV(), S.getExpr(), S.getUpdateExpr(),
3624 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003625 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003626 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003627 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003628}
3629
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003630static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3631 const OMPExecutableDirective &S,
3632 const RegionCodeGenTy &CodeGen) {
3633 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3634 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003635 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3636
Samuel Antaoee8fb302016-01-06 13:42:12 +00003637 llvm::Function *Fn = nullptr;
3638 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003639
Samuel Antaobed3c462015-10-02 16:14:20 +00003640 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003641 // Check for the at most one if clause associated with the target region.
3642 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3643 if (C->getNameModifier() == OMPD_unknown ||
3644 C->getNameModifier() == OMPD_target) {
3645 IfCond = C->getCondition();
3646 break;
3647 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003648 }
3649
3650 // Check if we have any device clause associated with the directive.
3651 const Expr *Device = nullptr;
3652 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3653 Device = C->getDevice();
3654 }
3655
Samuel Antaoee8fb302016-01-06 13:42:12 +00003656 // Check if we have an if clause whose conditional always evaluates to false
3657 // or if we do not have any targets specified. If so the target region is not
3658 // an offload entry point.
3659 bool IsOffloadEntry = true;
3660 if (IfCond) {
3661 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003662 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663 IsOffloadEntry = false;
3664 }
3665 if (CGM.getLangOpts().OMPTargetTriples.empty())
3666 IsOffloadEntry = false;
3667
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003668 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003669 StringRef ParentName;
3670 // In case we have Ctors/Dtors we use the complete type variant to produce
3671 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003672 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003673 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003674 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003675 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3676 else
3677 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003678 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003680 // Emit target region as a standalone region.
3681 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3682 IsOffloadEntry, CodeGen);
3683 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003684 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3685 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003686 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003687 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003688}
3689
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003690static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3691 PrePostActionTy &Action) {
3692 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3693 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3694 CGF.EmitOMPPrivateClause(S, PrivateScope);
3695 (void)PrivateScope.Privatize();
3696
3697 Action.Enter(CGF);
3698 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3699}
3700
3701void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3702 StringRef ParentName,
3703 const OMPTargetDirective &S) {
3704 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3705 emitTargetRegion(CGF, S, Action);
3706 };
3707 llvm::Function *Fn;
3708 llvm::Constant *Addr;
3709 // Emit target region as a standalone region.
3710 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3711 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3712 assert(Fn && Addr && "Target device function emission failed.");
3713}
3714
3715void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3716 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3717 emitTargetRegion(CGF, S, Action);
3718 };
3719 emitCommonOMPTargetDirective(*this, S, CodeGen);
3720}
3721
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003722static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3723 const OMPExecutableDirective &S,
3724 OpenMPDirectiveKind InnermostKind,
3725 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003726 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3727 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3728 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003729
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003730 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3731 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003732 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003733 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3734 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003735
Carlo Bertollic6872252016-04-04 15:55:02 +00003736 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3737 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003738 }
3739
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003740 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003741 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3742 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003743 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3744 CapturedVars);
3745}
3746
3747void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003748 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003749 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003750 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003751 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3752 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003753 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003754 (void)PrivateScope.Privatize();
3755 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003756 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003757 };
3758 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003759 emitPostUpdateForReductionClause(
3760 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003761}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003762
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003763static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3764 const OMPTargetTeamsDirective &S) {
3765 auto *CS = S.getCapturedStmt(OMPD_teams);
3766 Action.Enter(CGF);
3767 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3768 // TODO: Add support for clauses.
3769 CGF.EmitStmt(CS->getCapturedStmt());
3770 };
3771 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3772}
3773
3774void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3775 CodeGenModule &CGM, StringRef ParentName,
3776 const OMPTargetTeamsDirective &S) {
3777 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3778 emitTargetTeamsRegion(CGF, Action, S);
3779 };
3780 llvm::Function *Fn;
3781 llvm::Constant *Addr;
3782 // Emit target region as a standalone region.
3783 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3784 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3785 assert(Fn && Addr && "Target device function emission failed.");
3786}
3787
3788void CodeGenFunction::EmitOMPTargetTeamsDirective(
3789 const OMPTargetTeamsDirective &S) {
3790 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3791 emitTargetTeamsRegion(CGF, Action, S);
3792 };
3793 emitCommonOMPTargetDirective(*this, S, CodeGen);
3794}
3795
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003796void CodeGenFunction::EmitOMPCancellationPointDirective(
3797 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003798 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3799 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003800}
3801
Alexey Bataev80909872015-07-02 11:25:17 +00003802void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003803 const Expr *IfCond = nullptr;
3804 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3805 if (C->getNameModifier() == OMPD_unknown ||
3806 C->getNameModifier() == OMPD_cancel) {
3807 IfCond = C->getCondition();
3808 break;
3809 }
3810 }
3811 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003812 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003813}
3814
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003815CodeGenFunction::JumpDest
3816CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003817 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3818 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003819 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003820 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003821 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3822 Kind == OMPD_distribute_parallel_for ||
3823 Kind == OMPD_target_parallel_for);
3824 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003825}
Michael Wong65f367f2015-07-21 13:44:28 +00003826
Samuel Antaocc10b852016-07-28 14:23:26 +00003827void CodeGenFunction::EmitOMPUseDevicePtrClause(
3828 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3829 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3830 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3831 auto OrigVarIt = C.varlist_begin();
3832 auto InitIt = C.inits().begin();
3833 for (auto PvtVarIt : C.private_copies()) {
3834 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3835 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3836 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3837
3838 // In order to identify the right initializer we need to match the
3839 // declaration used by the mapping logic. In some cases we may get
3840 // OMPCapturedExprDecl that refers to the original declaration.
3841 const ValueDecl *MatchingVD = OrigVD;
3842 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3843 // OMPCapturedExprDecl are used to privative fields of the current
3844 // structure.
3845 auto *ME = cast<MemberExpr>(OED->getInit());
3846 assert(isa<CXXThisExpr>(ME->getBase()) &&
3847 "Base should be the current struct!");
3848 MatchingVD = ME->getMemberDecl();
3849 }
3850
3851 // If we don't have information about the current list item, move on to
3852 // the next one.
3853 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3854 if (InitAddrIt == CaptureDeviceAddrMap.end())
3855 continue;
3856
3857 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3858 // Initialize the temporary initialization variable with the address we
3859 // get from the runtime library. We have to cast the source address
3860 // because it is always a void *. References are materialized in the
3861 // privatization scope, so the initialization here disregards the fact
3862 // the original variable is a reference.
3863 QualType AddrQTy =
3864 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3865 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3866 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3867 setAddrOfLocalVar(InitVD, InitAddr);
3868
3869 // Emit private declaration, it will be initialized by the value we
3870 // declaration we just added to the local declarations map.
3871 EmitDecl(*PvtVD);
3872
3873 // The initialization variables reached its purpose in the emission
3874 // ofthe previous declaration, so we don't need it anymore.
3875 LocalDeclMap.erase(InitVD);
3876
3877 // Return the address of the private variable.
3878 return GetAddrOfLocalVar(PvtVD);
3879 });
3880 assert(IsRegistered && "firstprivate var already registered as private");
3881 // Silence the warning about unused variable.
3882 (void)IsRegistered;
3883
3884 ++OrigVarIt;
3885 ++InitIt;
3886 }
3887}
3888
Michael Wong65f367f2015-07-21 13:44:28 +00003889// Generate the instructions for '#pragma omp target data' directive.
3890void CodeGenFunction::EmitOMPTargetDataDirective(
3891 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003892 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3893
3894 // Create a pre/post action to signal the privatization of the device pointer.
3895 // This action can be replaced by the OpenMP runtime code generation to
3896 // deactivate privatization.
3897 bool PrivatizeDevicePointers = false;
3898 class DevicePointerPrivActionTy : public PrePostActionTy {
3899 bool &PrivatizeDevicePointers;
3900
3901 public:
3902 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3903 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3904 void Enter(CodeGenFunction &CGF) override {
3905 PrivatizeDevicePointers = true;
3906 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003907 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003908 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3909
3910 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3911 CodeGenFunction &CGF, PrePostActionTy &Action) {
3912 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3913 CGF.EmitStmt(
3914 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3915 };
3916
3917 // Codegen that selects wheather to generate the privatization code or not.
3918 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3919 &InnermostCodeGen](CodeGenFunction &CGF,
3920 PrePostActionTy &Action) {
3921 RegionCodeGenTy RCG(InnermostCodeGen);
3922 PrivatizeDevicePointers = false;
3923
3924 // Call the pre-action to change the status of PrivatizeDevicePointers if
3925 // needed.
3926 Action.Enter(CGF);
3927
3928 if (PrivatizeDevicePointers) {
3929 OMPPrivateScope PrivateScope(CGF);
3930 // Emit all instances of the use_device_ptr clause.
3931 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3932 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3933 Info.CaptureDeviceAddrMap);
3934 (void)PrivateScope.Privatize();
3935 RCG(CGF);
3936 } else
3937 RCG(CGF);
3938 };
3939
3940 // Forward the provided action to the privatization codegen.
3941 RegionCodeGenTy PrivRCG(PrivCodeGen);
3942 PrivRCG.setAction(Action);
3943
3944 // Notwithstanding the body of the region is emitted as inlined directive,
3945 // we don't use an inline scope as changes in the references inside the
3946 // region are expected to be visible outside, so we do not privative them.
3947 OMPLexicalScope Scope(CGF, S);
3948 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3949 PrivRCG);
3950 };
3951
3952 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003953
3954 // If we don't have target devices, don't bother emitting the data mapping
3955 // code.
3956 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003957 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003958 return;
3959 }
3960
3961 // Check if we have any if clause associated with the directive.
3962 const Expr *IfCond = nullptr;
3963 if (auto *C = S.getSingleClause<OMPIfClause>())
3964 IfCond = C->getCondition();
3965
3966 // Check if we have any device clause associated with the directive.
3967 const Expr *Device = nullptr;
3968 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3969 Device = C->getDevice();
3970
Samuel Antaocc10b852016-07-28 14:23:26 +00003971 // Set the action to signal privatization of device pointers.
3972 RCG.setAction(PrivAction);
3973
3974 // Emit region code.
3975 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3976 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003977}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003978
Samuel Antaodf67fc42016-01-19 19:15:56 +00003979void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3980 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003981 // If we don't have target devices, don't bother emitting the data mapping
3982 // code.
3983 if (CGM.getLangOpts().OMPTargetTriples.empty())
3984 return;
3985
3986 // Check if we have any if clause associated with the directive.
3987 const Expr *IfCond = nullptr;
3988 if (auto *C = S.getSingleClause<OMPIfClause>())
3989 IfCond = C->getCondition();
3990
3991 // Check if we have any device clause associated with the directive.
3992 const Expr *Device = nullptr;
3993 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3994 Device = C->getDevice();
3995
Samuel Antao8d2d7302016-05-26 18:30:22 +00003996 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003997}
3998
Samuel Antao72590762016-01-19 20:04:50 +00003999void CodeGenFunction::EmitOMPTargetExitDataDirective(
4000 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004001 // If we don't have target devices, don't bother emitting the data mapping
4002 // code.
4003 if (CGM.getLangOpts().OMPTargetTriples.empty())
4004 return;
4005
4006 // Check if we have any if clause associated with the directive.
4007 const Expr *IfCond = nullptr;
4008 if (auto *C = S.getSingleClause<OMPIfClause>())
4009 IfCond = C->getCondition();
4010
4011 // Check if we have any device clause associated with the directive.
4012 const Expr *Device = nullptr;
4013 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4014 Device = C->getDevice();
4015
Samuel Antao8d2d7302016-05-26 18:30:22 +00004016 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004017}
4018
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004019static void emitTargetParallelRegion(CodeGenFunction &CGF,
4020 const OMPTargetParallelDirective &S,
4021 PrePostActionTy &Action) {
4022 // Get the captured statement associated with the 'parallel' region.
4023 auto *CS = S.getCapturedStmt(OMPD_parallel);
4024 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004025 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4026 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4027 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4028 CGF.EmitOMPPrivateClause(S, PrivateScope);
4029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4030 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004031 // TODO: Add support for clauses.
4032 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004033 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004034 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004035 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4036 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004037 emitPostUpdateForReductionClause(
4038 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004039}
4040
4041void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4042 CodeGenModule &CGM, StringRef ParentName,
4043 const OMPTargetParallelDirective &S) {
4044 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4045 emitTargetParallelRegion(CGF, S, Action);
4046 };
4047 llvm::Function *Fn;
4048 llvm::Constant *Addr;
4049 // Emit target region as a standalone region.
4050 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4051 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4052 assert(Fn && Addr && "Target device function emission failed.");
4053}
4054
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004055void CodeGenFunction::EmitOMPTargetParallelDirective(
4056 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004057 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4058 emitTargetParallelRegion(CGF, S, Action);
4059 };
4060 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004061}
4062
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004063void CodeGenFunction::EmitOMPTargetParallelForDirective(
4064 const OMPTargetParallelForDirective &S) {
4065 // TODO: codegen for target parallel for.
4066}
4067
Alexey Bataev7292c292016-04-25 12:22:29 +00004068/// Emit a helper variable and return corresponding lvalue.
4069static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4070 const ImplicitParamDecl *PVD,
4071 CodeGenFunction::OMPPrivateScope &Privates) {
4072 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4073 Privates.addPrivate(
4074 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4075}
4076
4077void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4078 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4079 // Emit outlined function for task construct.
4080 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4081 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4082 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4083 const Expr *IfCond = nullptr;
4084 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4085 if (C->getNameModifier() == OMPD_unknown ||
4086 C->getNameModifier() == OMPD_taskloop) {
4087 IfCond = C->getCondition();
4088 break;
4089 }
4090 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004091
4092 OMPTaskDataTy Data;
4093 // Check if taskloop must be emitted without taskgroup.
4094 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004095 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004096 Data.Tied = true;
4097 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004098 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4099 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004100 Data.Schedule.setInt(/*IntVal=*/false);
4101 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004102 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4103 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004104 Data.Schedule.setInt(/*IntVal=*/true);
4105 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004106 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004107
4108 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4109 // if (PreCond) {
4110 // for (IV in 0..LastIteration) BODY;
4111 // <Final counter/linear vars updates>;
4112 // }
4113 //
4114
4115 // Emit: if (PreCond) - begin.
4116 // If the condition constant folds and can be elided, avoid emitting the
4117 // whole loop.
4118 bool CondConstant;
4119 llvm::BasicBlock *ContBlock = nullptr;
4120 OMPLoopScope PreInitScope(CGF, S);
4121 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4122 if (!CondConstant)
4123 return;
4124 } else {
4125 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4126 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4127 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4128 CGF.getProfileCount(&S));
4129 CGF.EmitBlock(ThenBlock);
4130 CGF.incrementProfileCounter(&S);
4131 }
4132
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004133 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4134 CGF.EmitOMPSimdInit(S);
4135
Alexey Bataev7292c292016-04-25 12:22:29 +00004136 OMPPrivateScope LoopScope(CGF);
4137 // Emit helper vars inits.
4138 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4139 auto *I = CS->getCapturedDecl()->param_begin();
4140 auto *LBP = std::next(I, LowerBound);
4141 auto *UBP = std::next(I, UpperBound);
4142 auto *STP = std::next(I, Stride);
4143 auto *LIP = std::next(I, LastIter);
4144 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4145 LoopScope);
4146 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4147 LoopScope);
4148 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4149 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4150 LoopScope);
4151 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004152 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004153 (void)LoopScope.Privatize();
4154 // Emit the loop iteration variable.
4155 const Expr *IVExpr = S.getIterationVariable();
4156 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4157 CGF.EmitVarDecl(*IVDecl);
4158 CGF.EmitIgnoredExpr(S.getInit());
4159
4160 // Emit the iterations count variable.
4161 // If it is not a variable, Sema decided to calculate iterations count on
4162 // each iteration (e.g., it is foldable into a constant).
4163 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4164 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4165 // Emit calculation of the iterations count.
4166 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4167 }
4168
4169 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4170 S.getInc(),
4171 [&S](CodeGenFunction &CGF) {
4172 CGF.EmitOMPLoopBody(S, JumpDest());
4173 CGF.EmitStopPoint(&S);
4174 },
4175 [](CodeGenFunction &) {});
4176 // Emit: if (PreCond) - end.
4177 if (ContBlock) {
4178 CGF.EmitBranch(ContBlock);
4179 CGF.EmitBlock(ContBlock, true);
4180 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004181 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4182 if (HasLastprivateClause) {
4183 CGF.EmitOMPLastprivateClauseFinal(
4184 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4185 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4186 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4187 (*LIP)->getType(), S.getLocStart())));
4188 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004189 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004190 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4191 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4192 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004193 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4194 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004195 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4196 OutlinedFn, SharedsTy,
4197 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004198 };
4199 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4200 CodeGen);
4201 };
Alexey Bataev33446032017-07-12 18:09:32 +00004202 if (Data.Nogroup)
4203 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4204 else {
4205 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4206 *this,
4207 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4208 PrePostActionTy &Action) {
4209 Action.Enter(CGF);
4210 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4211 },
4212 S.getLocStart());
4213 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004214}
4215
Alexey Bataev49f6e782015-12-01 04:18:41 +00004216void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004217 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004218}
4219
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004220void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4221 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004222 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004223}
Samuel Antao686c70c2016-05-26 17:30:50 +00004224
4225// Generate the instructions for '#pragma omp target update' directive.
4226void CodeGenFunction::EmitOMPTargetUpdateDirective(
4227 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004228 // If we don't have target devices, don't bother emitting the data mapping
4229 // code.
4230 if (CGM.getLangOpts().OMPTargetTriples.empty())
4231 return;
4232
4233 // Check if we have any if clause associated with the directive.
4234 const Expr *IfCond = nullptr;
4235 if (auto *C = S.getSingleClause<OMPIfClause>())
4236 IfCond = C->getCondition();
4237
4238 // Check if we have any device clause associated with the directive.
4239 const Expr *Device = nullptr;
4240 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4241 Device = C->getDevice();
4242
4243 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004244}