blob: 22269e42c7a0083232a9eadb510956aa6092886b [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();
90 return !isOpenMPTargetExecutionDirective(Kind) &&
91 isOpenMPParallelDirective(Kind);
92 }
93
94public:
95 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
96 : OMPLexicalScope(CGF, S,
97 /*AsInlined=*/false,
98 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
99};
100
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000101/// Lexical scope for OpenMP teams construct, that handles correct codegen
102/// for captured expressions.
103class OMPTeamsScope final : public OMPLexicalScope {
104 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
105 OpenMPDirectiveKind Kind = S.getDirectiveKind();
106 return !isOpenMPTargetExecutionDirective(Kind) &&
107 isOpenMPTeamsDirective(Kind);
108 }
109
110public:
111 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
112 : OMPLexicalScope(CGF, S,
113 /*AsInlined=*/false,
114 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
115};
116
Alexey Bataev5a3af132016-03-29 08:58:54 +0000117/// Private scope for OpenMP loop-based directives, that supports capturing
118/// of used expression from loop statement.
119class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
120 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
121 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
122 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
123 for (const auto *I : PreInits->decls())
124 CGF.EmitVarDecl(cast<VarDecl>(*I));
125 }
126 }
127 }
128
129public:
130 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
131 : CodeGenFunction::RunCleanupsScope(CGF) {
132 emitPreInitStmt(CGF, S);
133 }
134};
135
Alexey Bataev3392d762016-02-16 11:18:12 +0000136} // namespace
137
Alexey Bataev1189bd02016-01-26 12:20:39 +0000138llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
139 auto &C = getContext();
140 llvm::Value *Size = nullptr;
141 auto SizeInChars = C.getTypeSizeInChars(Ty);
142 if (SizeInChars.isZero()) {
143 // getTypeSizeInChars() returns 0 for a VLA.
144 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
145 llvm::Value *ArraySize;
146 std::tie(ArraySize, Ty) = getVLASize(VAT);
147 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
148 }
149 SizeInChars = C.getTypeSizeInChars(Ty);
150 if (SizeInChars.isZero())
151 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
152 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
153 } else
154 Size = CGM.getSize(SizeInChars);
155 return Size;
156}
157
Alexey Bataev2377fe92015-09-10 08:12:02 +0000158void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000159 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000160 const RecordDecl *RD = S.getCapturedRecordDecl();
161 auto CurField = RD->field_begin();
162 auto CurCap = S.captures().begin();
163 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
164 E = S.capture_init_end();
165 I != E; ++I, ++CurField, ++CurCap) {
166 if (CurField->hasCapturedVLAType()) {
167 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000168 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000170 } else if (CurCap->capturesThis())
171 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000172 else if (CurCap->capturesVariableByCopy()) {
173 llvm::Value *CV =
174 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
175
176 // If the field is not a pointer, we need to save the actual value
177 // and load it as a void pointer.
178 if (!CurField->getType()->isAnyPointerType()) {
179 auto &Ctx = getContext();
180 auto DstAddr = CreateMemTemp(
181 Ctx.getUIntPtrType(),
182 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
183 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
184
185 auto *SrcAddrVal = EmitScalarConversion(
186 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
187 Ctx.getPointerType(CurField->getType()), SourceLocation());
188 LValue SrcLV =
189 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
190
191 // Store the value using the source type pointer.
192 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
193
194 // Load the value using the destination type pointer.
195 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
196 }
197 CapturedVars.push_back(CV);
198 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000200 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000201 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 }
203}
204
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000205static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
206 StringRef Name, LValue AddrLV,
207 bool isReferenceType = false) {
208 ASTContext &Ctx = CGF.getContext();
209
210 auto *CastedPtr = CGF.EmitScalarConversion(
211 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
212 Ctx.getPointerType(DstType), SourceLocation());
213 auto TmpAddr =
214 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
215 .getAddress();
216
217 // If we are dealing with references we need to return the address of the
218 // reference instead of the reference of the value.
219 if (isReferenceType) {
220 QualType RefType = Ctx.getLValueReferenceType(DstType);
221 auto *RefVal = TmpAddr.getPointer();
222 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
223 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000224 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225 }
226
227 return TmpAddr;
228}
229
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000230static QualType getCanonicalParamType(ASTContext &C, QualType T) {
231 if (T->isLValueReferenceType()) {
232 return C.getLValueReferenceType(
233 getCanonicalParamType(C, T.getNonReferenceType()),
234 /*SpelledAsLValue=*/false);
235 }
236 if (T->isPointerType())
237 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
238 return C.getCanonicalParamType(T);
239}
240
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000242CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000243 assert(
244 CapturedStmtInfo &&
245 "CapturedStmtInfo should be set when generating the captured function");
246 const CapturedDecl *CD = S.getCapturedDecl();
247 const RecordDecl *RD = S.getCapturedRecordDecl();
248 assert(CD->hasBody() && "missing CapturedDecl body");
249
250 // Build the argument list.
251 ASTContext &Ctx = CGM.getContext();
252 FunctionArgList Args;
253 Args.append(CD->param_begin(),
254 std::next(CD->param_begin(), CD->getContextParamPosition()));
255 auto I = S.captures().begin();
256 for (auto *FD : RD->fields()) {
257 QualType ArgType = FD->getType();
258 IdentifierInfo *II = nullptr;
259 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000260
261 // If this is a capture by copy and the type is not a pointer, the outlined
262 // function argument type should be uintptr and the value properly casted to
263 // uintptr. This is necessary given that the runtime library is only able to
264 // deal with pointers. We can pass in the same way the VLA type sizes to the
265 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000266 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
267 I->capturesVariableArrayType())
268 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000269
270 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000271 CapVar = I->getCapturedVar();
272 II = CapVar->getIdentifier();
273 } else if (I->capturesThis())
274 II = &getContext().Idents.get("this");
275 else {
276 assert(I->capturesVariableArrayType());
277 II = &getContext().Idents.get("vla");
278 }
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000279 if (ArgType->isVariablyModifiedType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000280 ArgType =
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000281 getCanonicalParamType(getContext(), ArgType.getNonReferenceType());
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000282 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000283 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
284 FD->getLocation(), II, ArgType));
285 ++I;
286 }
287 Args.append(
288 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
289 CD->param_end());
290
291 // Create the function declaration.
292 FunctionType::ExtInfo ExtInfo;
293 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000294 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
296
297 llvm::Function *F = llvm::Function::Create(
298 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
299 CapturedStmtInfo->getHelperName(), &CGM.getModule());
300 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
301 if (CD->isNothrow())
302 F->addFnAttr(llvm::Attribute::NoUnwind);
303
304 // Generate the function.
305 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
306 CD->getBody()->getLocStart());
307 unsigned Cnt = CD->getContextParamPosition();
308 I = S.captures().begin();
309 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000310 // If we are capturing a pointer by copy we don't need to do anything, just
311 // use the value that we get from the arguments.
312 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000313 const VarDecl *CurVD = I->getCapturedVar();
314 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
315 // If the variable is a reference we need to materialize it here.
316 if (CurVD->getType()->isReferenceType()) {
317 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
318 ".materialized_ref");
319 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
320 CurVD->getType());
321 LocalAddr = RefAddr;
322 }
323 setAddrOfLocalVar(CurVD, LocalAddr);
Richard Trieucc3949d2016-02-18 22:34:54 +0000324 ++Cnt;
325 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000326 continue;
327 }
328
Alexey Bataev2377fe92015-09-10 08:12:02 +0000329 LValue ArgLVal =
330 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
331 AlignmentSource::Decl);
332 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000333 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000334 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
335 Args[Cnt]->getName(), ArgLVal),
336 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000337 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000338 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000339 auto VAT = FD->getCapturedVLAType();
340 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
341 } else if (I->capturesVariable()) {
342 auto *Var = I->getCapturedVar();
343 QualType VarTy = Var->getType();
344 Address ArgAddr = ArgLVal.getAddress();
345 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000346 if (ArgLVal.getType()->isLValueReferenceType()) {
347 ArgAddr = EmitLoadOfReference(
348 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000349 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000350 assert(ArgLVal.getType()->isPointerType());
351 ArgAddr = EmitLoadOfPointer(
352 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
353 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000354 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000355 setAddrOfLocalVar(
356 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000357 } else if (I->capturesVariableByCopy()) {
358 assert(!FD->getType()->isAnyPointerType() &&
359 "Not expecting a captured pointer.");
360 auto *Var = I->getCapturedVar();
361 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000362 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
363 Args[Cnt]->getName(), ArgLVal,
364 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000365 } else {
366 // If 'this' is captured, load it into CXXThisValue.
367 assert(I->capturesThis());
368 CXXThisValue =
369 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
370 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000371 ++Cnt;
372 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 }
374
Serge Pavlov3a561452015-12-06 14:32:39 +0000375 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 CapturedStmtInfo->EmitBody(*this, CD->getBody());
377 FinishFunction(CD->getBodyRBrace());
378
379 return F;
380}
381
Alexey Bataev9959db52014-05-06 10:08:46 +0000382//===----------------------------------------------------------------------===//
383// OpenMP Directive Emission
384//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000385void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000386 Address DestAddr, Address SrcAddr, QualType OriginalType,
387 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000388 // Perform element-by-element initialization.
389 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000390
391 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000392 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000393 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
394 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
395
396 auto SrcBegin = SrcAddr.getPointer();
397 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000398 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
400 // The basic structure here is a while-do loop.
401 auto BodyBB = createBasicBlock("omp.arraycpy.body");
402 auto DoneBB = createBasicBlock("omp.arraycpy.done");
403 auto IsEmpty =
404 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
405 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000406
Alexey Bataev420d45b2015-04-14 05:11:24 +0000407 // Enter the loop body, making that address the current address.
408 auto EntryBB = Builder.GetInsertBlock();
409 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000410
411 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
412
413 llvm::PHINode *SrcElementPHI =
414 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
415 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
416 Address SrcElementCurrent =
417 Address(SrcElementPHI,
418 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
419
420 llvm::PHINode *DestElementPHI =
421 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
422 DestElementPHI->addIncoming(DestBegin, EntryBB);
423 Address DestElementCurrent =
424 Address(DestElementPHI,
425 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000426
Alexey Bataev420d45b2015-04-14 05:11:24 +0000427 // Emit copy.
428 CopyGen(DestElementCurrent, SrcElementCurrent);
429
430 // Shift the address forward by one element.
431 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000432 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000433 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000434 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000435 // Check whether we've reached the end.
436 auto Done =
437 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
438 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000439 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
440 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000441
442 // Done.
443 EmitBlock(DoneBB, /*IsFinished=*/true);
444}
445
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000446/// Check if the combiner is a call to UDR combiner and if it is so return the
447/// UDR decl used for reduction.
448static const OMPDeclareReductionDecl *
449getReductionInit(const Expr *ReductionOp) {
450 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
451 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
452 if (auto *DRE =
453 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
454 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
455 return DRD;
456 return nullptr;
457}
458
459static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
460 const OMPDeclareReductionDecl *DRD,
461 const Expr *InitOp,
462 Address Private, Address Original,
463 QualType Ty) {
464 if (DRD->getInitializer()) {
465 std::pair<llvm::Function *, llvm::Function *> Reduction =
466 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
467 auto *CE = cast<CallExpr>(InitOp);
468 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
469 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
470 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
471 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
472 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
473 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
474 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
475 [=]() -> Address { return Private; });
476 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
477 [=]() -> Address { return Original; });
478 (void)PrivateScope.Privatize();
479 RValue Func = RValue::get(Reduction.second);
480 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
481 CGF.EmitIgnoredExpr(InitOp);
482 } else {
483 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
484 auto *GV = new llvm::GlobalVariable(
485 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
486 llvm::GlobalValue::PrivateLinkage, Init, ".init");
487 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
488 RValue InitRVal;
489 switch (CGF.getEvaluationKind(Ty)) {
490 case TEK_Scalar:
491 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
492 break;
493 case TEK_Complex:
494 InitRVal =
495 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
496 break;
497 case TEK_Aggregate:
498 InitRVal = RValue::getAggregate(LV.getAddress());
499 break;
500 }
501 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
502 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
503 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
504 /*IsInitializer=*/false);
505 }
506}
507
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000508/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000509/// \param DestAddr Address of the array.
510/// \param Type Type of array.
511/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000512/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000513static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000514 QualType Type, const Expr *Init,
515 Address SrcAddr = Address::invalid()) {
516 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000517 // Perform element-by-element initialization.
518 QualType ElementTy;
519
520 // Drill down to the base element type on both arrays.
521 auto ArrayTy = Type->getAsArrayTypeUnsafe();
522 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
523 DestAddr =
524 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000525 if (DRD)
526 SrcAddr =
527 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000528
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000529 llvm::Value *SrcBegin = nullptr;
530 if (DRD)
531 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000532 auto DestBegin = DestAddr.getPointer();
533 // Cast from pointer to array type to pointer to single element.
534 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
535 // The basic structure here is a while-do loop.
536 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
537 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
538 auto IsEmpty =
539 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
540 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
541
542 // Enter the loop body, making that address the current address.
543 auto EntryBB = CGF.Builder.GetInsertBlock();
544 CGF.EmitBlock(BodyBB);
545
546 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
547
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000548 llvm::PHINode *SrcElementPHI = nullptr;
549 Address SrcElementCurrent = Address::invalid();
550 if (DRD) {
551 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
552 "omp.arraycpy.srcElementPast");
553 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
554 SrcElementCurrent =
555 Address(SrcElementPHI,
556 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
557 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000558 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
559 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
560 DestElementPHI->addIncoming(DestBegin, EntryBB);
561 Address DestElementCurrent =
562 Address(DestElementPHI,
563 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
564
565 // Emit copy.
566 {
567 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000568 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000569 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
570 SrcElementCurrent, ElementTy);
571 } else
572 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
573 /*IsInitializer=*/false);
574 }
575
576 if (DRD) {
577 // Shift the address forward by one element.
578 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
579 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
580 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000581 }
582
583 // Shift the address forward by one element.
584 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
585 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
586 // Check whether we've reached the end.
587 auto Done =
588 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
589 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
590 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
591
592 // Done.
593 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
594}
595
John McCall7f416cc2015-09-08 08:05:57 +0000596void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
597 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000598 const VarDecl *SrcVD, const Expr *Copy) {
599 if (OriginalType->isArrayType()) {
600 auto *BO = dyn_cast<BinaryOperator>(Copy);
601 if (BO && BO->getOpcode() == BO_Assign) {
602 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000603 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000604 } else {
605 // For arrays with complex element types perform element by element
606 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000607 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000608 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000609 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000610 // Working with the single array element, so have to remap
611 // destination and source variables to corresponding array
612 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000613 CodeGenFunction::OMPPrivateScope Remap(*this);
614 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000615 return DestElement;
616 });
617 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000618 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000619 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000620 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000621 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000622 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000623 } else {
624 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000625 CodeGenFunction::OMPPrivateScope Remap(*this);
626 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
627 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628 (void)Remap.Privatize();
629 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000630 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000631 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000632}
633
Alexey Bataev69c62a92015-04-15 04:52:20 +0000634bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
635 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000636 if (!HaveInsertPoint())
637 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000638 bool FirstprivateIsLastprivate = false;
639 llvm::DenseSet<const VarDecl *> Lastprivates;
640 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
641 for (const auto *D : C->varlists())
642 Lastprivates.insert(
643 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
644 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000645 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000646 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000647 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000648 auto IRef = C->varlist_begin();
649 auto InitsRef = C->inits().begin();
650 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000651 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000652 bool ThisFirstprivateIsLastprivate =
653 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000654 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000655 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000656 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000657 !FD->getType()->isReferenceType()) {
658 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
659 ++IRef;
660 ++InitsRef;
661 continue;
662 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000663 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000664 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000665 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000666 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
667 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
668 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
670 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
671 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000672 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000673 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000674 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000675 // Emit VarDecl with copy init for arrays.
676 // Get the address of the original variable captured in current
677 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000678 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000679 auto Emission = EmitAutoVarAlloca(*VD);
680 auto *Init = VD->getInit();
681 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
682 // Perform simple memcpy.
683 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000684 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000685 } else {
686 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000687 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000688 [this, VDInit, Init](Address DestElement,
689 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000690 // Clean up any temporaries needed by the initialization.
691 RunCleanupsScope InitScope(*this);
692 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000693 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000694 EmitAnyExprToMem(Init, DestElement,
695 Init->getType().getQualifiers(),
696 /*IsInitializer*/ false);
697 LocalDeclMap.erase(VDInit);
698 });
699 }
700 EmitAutoVarCleanups(Emission);
701 return Emission.getAllocatedAddress();
702 });
703 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000704 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000705 // Emit private VarDecl with copy init.
706 // Remap temp VDInit variable to the address of the original
707 // variable
708 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000709 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000710 EmitDecl(*VD);
711 LocalDeclMap.erase(VDInit);
712 return GetAddrOfLocalVar(VD);
713 });
714 }
715 assert(IsRegistered &&
716 "firstprivate var already registered as private");
717 // Silence the warning about unused variable.
718 (void)IsRegistered;
719 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000720 ++IRef;
721 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000722 }
723 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000724 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725}
726
Alexey Bataev03b340a2014-10-21 03:16:40 +0000727void CodeGenFunction::EmitOMPPrivateClause(
728 const OMPExecutableDirective &D,
729 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000730 if (!HaveInsertPoint())
731 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000732 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000733 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000734 auto IRef = C->varlist_begin();
735 for (auto IInit : C->private_copies()) {
736 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000737 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
738 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
739 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000740 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000741 // Emit private VarDecl with copy init.
742 EmitDecl(*VD);
743 return GetAddrOfLocalVar(VD);
744 });
745 assert(IsRegistered && "private var already registered as private");
746 // Silence the warning about unused variable.
747 (void)IsRegistered;
748 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000749 ++IRef;
750 }
751 }
752}
753
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000754bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000755 if (!HaveInsertPoint())
756 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000757 // threadprivate_var1 = master_threadprivate_var1;
758 // operator=(threadprivate_var2, master_threadprivate_var2);
759 // ...
760 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000761 llvm::DenseSet<const VarDecl *> CopiedVars;
762 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000763 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000764 auto IRef = C->varlist_begin();
765 auto ISrcRef = C->source_exprs().begin();
766 auto IDestRef = C->destination_exprs().begin();
767 for (auto *AssignOp : C->assignment_ops()) {
768 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000769 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000770 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000771 // Get the address of the master variable. If we are emitting code with
772 // TLS support, the address is passed from the master as field in the
773 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000774 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000775 if (getLangOpts().OpenMPUseTLS &&
776 getContext().getTargetInfo().isTLSSupported()) {
777 assert(CapturedStmtInfo->lookup(VD) &&
778 "Copyin threadprivates should have been captured!");
779 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
780 VK_LValue, (*IRef)->getExprLoc());
781 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000782 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000783 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000784 MasterAddr =
785 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
786 : CGM.GetAddrOfGlobal(VD),
787 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000788 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000789 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000790 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000791 if (CopiedVars.size() == 1) {
792 // At first check if current thread is a master thread. If it is, no
793 // need to copy data.
794 CopyBegin = createBasicBlock("copyin.not.master");
795 CopyEnd = createBasicBlock("copyin.not.master.end");
796 Builder.CreateCondBr(
797 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000798 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
799 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000800 CopyBegin, CopyEnd);
801 EmitBlock(CopyBegin);
802 }
803 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
804 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000805 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000806 }
807 ++IRef;
808 ++ISrcRef;
809 ++IDestRef;
810 }
811 }
812 if (CopyEnd) {
813 // Exit out of copying procedure for non-master thread.
814 EmitBlock(CopyEnd, /*IsFinished=*/true);
815 return true;
816 }
817 return false;
818}
819
Alexey Bataev38e89532015-04-16 04:54:05 +0000820bool CodeGenFunction::EmitOMPLastprivateClauseInit(
821 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000822 if (!HaveInsertPoint())
823 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000824 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000825 llvm::DenseSet<const VarDecl *> SIMDLCVs;
826 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
827 auto *LoopDirective = cast<OMPLoopDirective>(&D);
828 for (auto *C : LoopDirective->counters()) {
829 SIMDLCVs.insert(
830 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
831 }
832 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000833 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000834 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000835 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000836 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
837 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000838 auto IRef = C->varlist_begin();
839 auto IDestRef = C->destination_exprs().begin();
840 for (auto *IInit : C->private_copies()) {
841 // Keep the address of the original variable for future update at the end
842 // of the loop.
843 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000844 // Taskloops do not require additional initialization, it is done in
845 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000846 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
847 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000848 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000849 DeclRefExpr DRE(
850 const_cast<VarDecl *>(OrigVD),
851 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
852 OrigVD) != nullptr,
853 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
854 return EmitLValue(&DRE).getAddress();
855 });
856 // Check if the variable is also a firstprivate: in this case IInit is
857 // not generated. Initialization of this variable will happen in codegen
858 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000859 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000860 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000861 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
862 // Emit private VarDecl with copy init.
863 EmitDecl(*VD);
864 return GetAddrOfLocalVar(VD);
865 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000866 assert(IsRegistered &&
867 "lastprivate var already registered as private");
868 (void)IsRegistered;
869 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000870 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000871 ++IRef;
872 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000873 }
874 }
875 return HasAtLeastOneLastprivate;
876}
877
878void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000879 const OMPExecutableDirective &D, bool NoFinals,
880 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000881 if (!HaveInsertPoint())
882 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000883 // Emit following code:
884 // if (<IsLastIterCond>) {
885 // orig_var1 = private_orig_var1;
886 // ...
887 // orig_varn = private_orig_varn;
888 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000889 llvm::BasicBlock *ThenBB = nullptr;
890 llvm::BasicBlock *DoneBB = nullptr;
891 if (IsLastIterCond) {
892 ThenBB = createBasicBlock(".omp.lastprivate.then");
893 DoneBB = createBasicBlock(".omp.lastprivate.done");
894 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
895 EmitBlock(ThenBB);
896 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000897 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
898 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000899 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000900 auto IC = LoopDirective->counters().begin();
901 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000902 auto *D =
903 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
904 if (NoFinals)
905 AlreadyEmittedVars.insert(D);
906 else
907 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000908 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000909 }
910 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000911 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
912 auto IRef = C->varlist_begin();
913 auto ISrcRef = C->source_exprs().begin();
914 auto IDestRef = C->destination_exprs().begin();
915 for (auto *AssignOp : C->assignment_ops()) {
916 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
917 QualType Type = PrivateVD->getType();
918 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
919 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
920 // If lastprivate variable is a loop control variable for loop-based
921 // directive, update its value before copyin back to original
922 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000923 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
924 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000925 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
926 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
927 // Get the address of the original variable.
928 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
929 // Get the address of the private variable.
930 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
931 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
932 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000933 Address(Builder.CreateLoad(PrivateAddr),
934 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000935 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000936 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000937 ++IRef;
938 ++ISrcRef;
939 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000940 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000941 if (auto *PostUpdate = C->getPostUpdateExpr())
942 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000943 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000944 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000945 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000946}
947
Alexey Bataev31300ed2016-02-04 11:27:03 +0000948static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
949 LValue BaseLV, llvm::Value *Addr) {
950 Address Tmp = Address::invalid();
951 Address TopTmp = Address::invalid();
952 Address MostTopTmp = Address::invalid();
953 BaseTy = BaseTy.getNonReferenceType();
954 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
955 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
956 Tmp = CGF.CreateMemTemp(BaseTy);
957 if (TopTmp.isValid())
958 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
959 else
960 MostTopTmp = Tmp;
961 TopTmp = Tmp;
962 BaseTy = BaseTy->getPointeeType();
963 }
964 llvm::Type *Ty = BaseLV.getPointer()->getType();
965 if (Tmp.isValid())
966 Ty = Tmp.getElementType();
967 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
968 if (Tmp.isValid()) {
969 CGF.Builder.CreateStore(Addr, Tmp);
970 return MostTopTmp;
971 }
972 return Address(Addr, BaseLV.getAlignment());
973}
974
975static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
976 LValue BaseLV) {
977 BaseTy = BaseTy.getNonReferenceType();
978 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
979 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
980 if (auto *PtrTy = BaseTy->getAs<PointerType>())
981 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
982 else {
983 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
984 BaseTy->castAs<ReferenceType>());
985 }
986 BaseTy = BaseTy->getPointeeType();
987 }
988 return CGF.MakeAddrLValue(
989 Address(
990 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
991 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
992 BaseLV.getAlignment()),
993 BaseLV.getType(), BaseLV.getAlignmentSource());
994}
995
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000996void CodeGenFunction::EmitOMPReductionClauseInit(
997 const OMPExecutableDirective &D,
998 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000999 if (!HaveInsertPoint())
1000 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001001 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001002 auto ILHS = C->lhs_exprs().begin();
1003 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001004 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001005 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001006 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001007 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001008 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1009 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001010 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001011 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
1012 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1013 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1014 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1015 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1016 Base = TempASE->getBase()->IgnoreParenImpCasts();
1017 auto *DE = cast<DeclRefExpr>(Base);
1018 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1019 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
1020 auto OASELValueUB =
1021 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
1022 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001023 LValue BaseLValue =
1024 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
1025 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001026 // Store the address of the original variable associated with the LHS
1027 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001028 PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001029 return OASELValueLB.getAddress();
1030 });
1031 // Emit reduction copy.
1032 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001033 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001034 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001035 // Emit VarDecl with copy init for arrays.
1036 // Get the address of the original variable captured in current
1037 // captured region.
1038 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
1039 OASELValueLB.getPointer());
1040 Size = Builder.CreateNUWAdd(
1041 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
1042 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1043 *this, cast<OpaqueValueExpr>(
1044 getContext()
1045 .getAsVariableArrayType(PrivateVD->getType())
1046 ->getSizeExpr()),
1047 RValue::get(Size));
1048 EmitVariablyModifiedType(PrivateVD->getType());
1049 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1050 auto Addr = Emission.getAllocatedAddress();
1051 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001052 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1053 DRD ? *IRed : Init,
1054 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001055 EmitAutoVarCleanups(Emission);
1056 // Emit private VarDecl with reduction init.
1057 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1058 OASELValueLB.getPointer());
1059 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001060 return castToBase(*this, OrigVD->getType(),
1061 OASELValueLB.getType(), OriginalBaseLValue,
1062 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001063 });
1064 assert(IsRegistered && "private var already registered as private");
1065 // Silence the warning about unused variable.
1066 (void)IsRegistered;
1067 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1068 return GetAddrOfLocalVar(PrivateVD);
1069 });
1070 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1071 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1072 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1073 Base = TempASE->getBase()->IgnoreParenImpCasts();
1074 auto *DE = cast<DeclRefExpr>(Base);
1075 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1076 auto ASELValue = EmitLValue(ASE);
1077 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001078 LValue BaseLValue = loadToBegin(
1079 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001080 // Store the address of the original variable associated with the LHS
1081 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001082 PrivateScope.addPrivate(
1083 LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001084 // Emit reduction copy.
1085 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001086 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001087 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001088 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001089 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1090 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001091 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001092 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1093 ASELValue.getAddress(),
1094 ASELValue.getType());
1095 } else
1096 EmitAutoVarInit(Emission);
1097 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001098 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1099 ASELValue.getPointer());
1100 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001101 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1102 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001103 });
1104 assert(IsRegistered && "private var already registered as private");
1105 // Silence the warning about unused variable.
1106 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001107 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1108 return Builder.CreateElementBitCast(
1109 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1110 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001111 });
1112 } else {
1113 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001114 QualType Type = PrivateVD->getType();
1115 if (getContext().getAsArrayType(Type)) {
1116 // Store the address of the original variable associated with the LHS
1117 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001118 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1119 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1120 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001121 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001122 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001123 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001124 OriginalAddr = Builder.CreateElementBitCast(
1125 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1126 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001127 });
1128 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1129 if (Type->isVariablyModifiedType()) {
1130 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1131 *this, cast<OpaqueValueExpr>(
1132 getContext()
1133 .getAsVariableArrayType(PrivateVD->getType())
1134 ->getSizeExpr()),
1135 RValue::get(
1136 getTypeSize(OrigVD->getType().getNonReferenceType())));
1137 EmitVariablyModifiedType(Type);
1138 }
1139 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1140 auto Addr = Emission.getAllocatedAddress();
1141 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001142 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1143 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001144 EmitAutoVarCleanups(Emission);
1145 return Emission.getAllocatedAddress();
1146 });
1147 assert(IsRegistered && "private var already registered as private");
1148 // Silence the warning about unused variable.
1149 (void)IsRegistered;
1150 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1151 return Builder.CreateElementBitCast(
1152 GetAddrOfLocalVar(PrivateVD),
1153 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1154 });
1155 } else {
1156 // Store the address of the original variable associated with the LHS
1157 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001158 Address OriginalAddr = Address::invalid();
1159 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1160 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001161 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1162 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1163 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001164 OriginalAddr = EmitLValue(&DRE).getAddress();
1165 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001166 });
1167 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001168 bool IsRegistered = PrivateScope.addPrivate(
1169 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001170 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001171 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1172 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001173 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001174 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1175 OriginalAddr,
1176 PrivateVD->getType());
1177 } else
1178 EmitAutoVarInit(Emission);
1179 EmitAutoVarCleanups(Emission);
1180 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001181 });
1182 assert(IsRegistered && "private var already registered as private");
1183 // Silence the warning about unused variable.
1184 (void)IsRegistered;
1185 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1186 return GetAddrOfLocalVar(PrivateVD);
1187 });
1188 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001189 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001190 ++ILHS;
1191 ++IRHS;
1192 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001193 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001194 }
1195 }
1196}
1197
1198void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001199 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001200 if (!HaveInsertPoint())
1201 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001202 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001203 llvm::SmallVector<const Expr *, 8> LHSExprs;
1204 llvm::SmallVector<const Expr *, 8> RHSExprs;
1205 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001206 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001207 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001208 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001209 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001210 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1211 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1212 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1213 }
1214 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001215 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1216 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1217 D.getDirectiveKind() == OMPD_simd;
1218 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001219 // Emit nowait reduction if nowait clause is present or directive is a
1220 // parallel directive (it always has implicit barrier).
1221 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001222 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001223 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001224 }
1225}
1226
Alexey Bataev61205072016-03-02 04:57:40 +00001227static void emitPostUpdateForReductionClause(
1228 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1229 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1230 if (!CGF.HaveInsertPoint())
1231 return;
1232 llvm::BasicBlock *DoneBB = nullptr;
1233 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1234 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1235 if (!DoneBB) {
1236 if (auto *Cond = CondGen(CGF)) {
1237 // If the first post-update expression is found, emit conditional
1238 // block if it was requested.
1239 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1240 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1241 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1242 CGF.EmitBlock(ThenBB);
1243 }
1244 }
1245 CGF.EmitIgnoredExpr(PostUpdate);
1246 }
1247 }
1248 if (DoneBB)
1249 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1250}
1251
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001252static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1253 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001254 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001255 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001256 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1257 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1258 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001259 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001260 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001261 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1262 /*IgnoreResultAssign*/ true);
1263 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1264 CGF, NumThreads, NumThreadsClause->getLocStart());
1265 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001266 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001267 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001268 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1269 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1270 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001271 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001272 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1273 if (C->getNameModifier() == OMPD_unknown ||
1274 C->getNameModifier() == OMPD_parallel) {
1275 IfCond = C->getCondition();
1276 break;
1277 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001278 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001279
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001280 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001281 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1282 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001283 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001284 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001285}
1286
1287void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001288 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001289 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001290 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001291 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001292 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1293 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001294 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001295 // propagation master's thread values of threadprivate variables to local
1296 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001297 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1298 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1299 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001300 }
1301 CGF.EmitOMPPrivateClause(S, PrivateScope);
1302 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1303 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001304 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001305 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001306 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001307 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001308 emitPostUpdateForReductionClause(
1309 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001310}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001311
Alexey Bataev0f34da12015-07-02 04:17:07 +00001312void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1313 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314 RunCleanupsScope BodyScope(*this);
1315 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001316 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001317 EmitIgnoredExpr(I);
1318 }
Alexander Musman3276a272015-03-21 10:12:56 +00001319 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001320 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001321 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001322 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001323 }
1324
Alexander Musmana5f070a2014-10-01 06:03:56 +00001325 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001326 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001327 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001328 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001329 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001330 // The end (updates/cleanups).
1331 EmitBlock(Continue.getBlock());
1332 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001333}
1334
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001335void CodeGenFunction::EmitOMPInnerLoop(
1336 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1337 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001338 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1339 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001340 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001341
1342 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001343 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001344 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001345 const SourceRange &R = S.getSourceRange();
1346 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1347 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348
1349 // If there are any cleanups between here and the loop-exit scope,
1350 // create a block to stage a loop exit along.
1351 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001352 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001353 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001354
Alexander Musmand196ef22014-10-07 08:57:09 +00001355 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001356
Alexey Bataev2df54a02015-03-12 08:53:29 +00001357 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001358 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001359 if (ExitBlock != LoopExit.getBlock()) {
1360 EmitBlock(ExitBlock);
1361 EmitBranchThroughCleanup(LoopExit);
1362 }
1363
1364 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001365 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001366
1367 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001368 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001369 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1370
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001371 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001372
1373 // Emit "IV = IV + 1" and a back-edge to the condition block.
1374 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001375 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001376 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001377 BreakContinueStack.pop_back();
1378 EmitBranch(CondBlock);
1379 LoopStack.pop();
1380 // Emit the fall-through block.
1381 EmitBlock(LoopExit.getBlock());
1382}
1383
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001384void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001385 if (!HaveInsertPoint())
1386 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001387 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001388 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001389 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001390 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001391 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1392 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1393 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1394 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1395 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1396 VD->getInit()->getType(), VK_LValue,
1397 VD->getInit()->getExprLoc());
1398 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1399 VD->getType()),
1400 /*capturedByInit=*/false);
1401 EmitAutoVarCleanups(Emission);
1402 } else
1403 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001404 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001405 // Emit the linear steps for the linear clauses.
1406 // If a step is not constant, it is pre-calculated before the loop.
1407 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1408 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001409 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001410 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001411 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001412 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001413 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001414}
1415
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001416void CodeGenFunction::EmitOMPLinearClauseFinal(
1417 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001418 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001419 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001420 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001421 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001422 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001423 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001424 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001425 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001426 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001427 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001428 // If the first post-update expression is found, emit conditional
1429 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001430 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1431 DoneBB = createBasicBlock(".omp.linear.pu.done");
1432 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1433 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001434 }
1435 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001436 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1437 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001438 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001439 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001440 Address OrigAddr = EmitLValue(&DRE).getAddress();
1441 CodeGenFunction::OMPPrivateScope VarScope(*this);
1442 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001443 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001444 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001445 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001446 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001447 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001448 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001449 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001450 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001451 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001452}
1453
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001454static void emitAlignedClause(CodeGenFunction &CGF,
1455 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001456 if (!CGF.HaveInsertPoint())
1457 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001458 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001459 unsigned ClauseAlignment = 0;
1460 if (auto AlignmentExpr = Clause->getAlignment()) {
1461 auto AlignmentCI =
1462 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1463 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001464 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001465 for (auto E : Clause->varlists()) {
1466 unsigned Alignment = ClauseAlignment;
1467 if (Alignment == 0) {
1468 // OpenMP [2.8.1, Description]
1469 // If no optional parameter is specified, implementation-defined default
1470 // alignments for SIMD instructions on the target platforms are assumed.
1471 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001472 CGF.getContext()
1473 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1474 E->getType()->getPointeeType()))
1475 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001476 }
1477 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1478 "alignment is not power of 2");
1479 if (Alignment != 0) {
1480 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1481 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1482 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001483 }
1484 }
1485}
1486
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001487void CodeGenFunction::EmitOMPPrivateLoopCounters(
1488 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1489 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001490 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001491 auto I = S.private_counters().begin();
1492 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001493 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1494 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001495 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001496 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001497 if (!LocalDeclMap.count(PrivateVD)) {
1498 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1499 EmitAutoVarCleanups(VarEmission);
1500 }
1501 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1502 /*RefersToEnclosingVariableOrCapture=*/false,
1503 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1504 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001505 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001506 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1507 VD->hasGlobalStorage()) {
1508 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1509 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1510 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1511 E->getType(), VK_LValue, E->getExprLoc());
1512 return EmitLValue(&DRE).getAddress();
1513 });
1514 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001515 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001516 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001517}
1518
Alexey Bataev62dbb972015-04-22 11:59:37 +00001519static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1520 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1521 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001522 if (!CGF.HaveInsertPoint())
1523 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001524 {
1525 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001526 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001527 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001528 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001529 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001530 CGF.EmitIgnoredExpr(I);
1531 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001532 }
1533 // Check that loop is executed at least one time.
1534 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1535}
1536
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001537void CodeGenFunction::EmitOMPLinearClause(
1538 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1539 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001540 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001541 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1542 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1543 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1544 for (auto *C : LoopDirective->counters()) {
1545 SIMDLCVs.insert(
1546 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1547 }
1548 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001549 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001550 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001551 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001552 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1553 auto *PrivateVD =
1554 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001555 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1556 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1557 // Emit private VarDecl with copy init.
1558 EmitVarDecl(*PrivateVD);
1559 return GetAddrOfLocalVar(PrivateVD);
1560 });
1561 assert(IsRegistered && "linear var already registered as private");
1562 // Silence the warning about unused variable.
1563 (void)IsRegistered;
1564 } else
1565 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001566 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001567 }
1568 }
1569}
1570
Alexey Bataev45bfad52015-08-21 12:19:04 +00001571static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001572 const OMPExecutableDirective &D,
1573 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001574 if (!CGF.HaveInsertPoint())
1575 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001576 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001577 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1578 /*ignoreResult=*/true);
1579 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1580 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1581 // In presence of finite 'safelen', it may be unsafe to mark all
1582 // the memory instructions parallel, because loop-carried
1583 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001584 if (!IsMonotonic)
1585 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001586 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001587 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1588 /*ignoreResult=*/true);
1589 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001590 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001591 // In presence of finite 'safelen', it may be unsafe to mark all
1592 // the memory instructions parallel, because loop-carried
1593 // dependences of 'safelen' iterations are possible.
1594 CGF.LoopStack.setParallel(false);
1595 }
1596}
1597
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001598void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1599 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001600 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001601 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001602 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001603 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001604}
1605
Alexey Bataevef549a82016-03-09 09:49:09 +00001606void CodeGenFunction::EmitOMPSimdFinal(
1607 const OMPLoopDirective &D,
1608 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001609 if (!HaveInsertPoint())
1610 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001611 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001612 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001613 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001614 for (auto F : D.finals()) {
1615 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001616 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1617 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1618 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1619 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001620 if (!DoneBB) {
1621 if (auto *Cond = CondGen(*this)) {
1622 // If the first post-update expression is found, emit conditional
1623 // block if it was requested.
1624 auto *ThenBB = createBasicBlock(".omp.final.then");
1625 DoneBB = createBasicBlock(".omp.final.done");
1626 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1627 EmitBlock(ThenBB);
1628 }
1629 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001630 Address OrigAddr = Address::invalid();
1631 if (CED)
1632 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1633 else {
1634 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1635 /*RefersToEnclosingVariableOrCapture=*/false,
1636 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1637 OrigAddr = EmitLValue(&DRE).getAddress();
1638 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001639 OMPPrivateScope VarScope(*this);
1640 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001641 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001642 (void)VarScope.Privatize();
1643 EmitIgnoredExpr(F);
1644 }
1645 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001646 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001647 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001648 if (DoneBB)
1649 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001650}
1651
Alexander Musman515ad8c2014-05-22 08:54:05 +00001652void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001653 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001654 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001655 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001656 // for (IV in 0..LastIteration) BODY;
1657 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001658 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001659 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001660
Alexey Bataev62dbb972015-04-22 11:59:37 +00001661 // Emit: if (PreCond) - begin.
1662 // If the condition constant folds and can be elided, avoid emitting the
1663 // whole loop.
1664 bool CondConstant;
1665 llvm::BasicBlock *ContBlock = nullptr;
1666 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1667 if (!CondConstant)
1668 return;
1669 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001670 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1671 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001672 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1673 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001674 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001675 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001676 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001677
1678 // Emit the loop iteration variable.
1679 const Expr *IVExpr = S.getIterationVariable();
1680 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1681 CGF.EmitVarDecl(*IVDecl);
1682 CGF.EmitIgnoredExpr(S.getInit());
1683
1684 // Emit the iterations count variable.
1685 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001686 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001687 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1688 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1689 // Emit calculation of the iterations count.
1690 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001691 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001692
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001693 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001694
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001695 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001696 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001697 {
1698 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001699 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1700 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001701 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001702 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001703 bool HasLastprivateClause =
1704 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001705 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001706 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1707 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001708 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001709 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001710 CGF.EmitStopPoint(&S);
1711 },
1712 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001713 CGF.EmitOMPSimdFinal(
1714 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001715 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001716 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001717 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001718 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001719 emitPostUpdateForReductionClause(
1720 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001721 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001722 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001723 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001724 // Emit: if (PreCond) - end.
1725 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001726 CGF.EmitBranch(ContBlock);
1727 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001728 }
1729 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001730 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001731 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001732}
1733
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001734void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001735 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1736 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001737 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001738
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001739 const Expr *IVExpr = S.getIterationVariable();
1740 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1741 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1742
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001743 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1744
1745 // Start the loop with a block that tests the condition.
1746 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1747 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001748 const SourceRange &R = S.getSourceRange();
1749 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1750 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001751
1752 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001753 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001754 // UB = min(UB, GlobalUB)
1755 EmitIgnoredExpr(S.getEnsureUpperBound());
1756 // IV = LB
1757 EmitIgnoredExpr(S.getInit());
1758 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001759 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001760 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001761 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1762 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001763 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001764
1765 // If there are any cleanups between here and the loop-exit scope,
1766 // create a block to stage a loop exit along.
1767 auto ExitBlock = LoopExit.getBlock();
1768 if (LoopScope.requiresCleanups())
1769 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1770
1771 auto LoopBody = createBasicBlock("omp.dispatch.body");
1772 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1773 if (ExitBlock != LoopExit.getBlock()) {
1774 EmitBlock(ExitBlock);
1775 EmitBranchThroughCleanup(LoopExit);
1776 }
1777 EmitBlock(LoopBody);
1778
Alexander Musman92bdaab2015-03-12 13:37:50 +00001779 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1780 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001781 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001782 EmitIgnoredExpr(S.getInit());
1783
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001784 // Create a block for the increment.
1785 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1786 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1787
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001788 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1789 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001790 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1791 LoopStack.setParallel(!IsMonotonic);
1792 else
1793 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001794
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001795 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001796 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1797 [&S, LoopExit](CodeGenFunction &CGF) {
1798 CGF.EmitOMPLoopBody(S, LoopExit);
1799 CGF.EmitStopPoint(&S);
1800 },
1801 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1802 if (Ordered) {
1803 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1804 CGF, Loc, IVSize, IVSigned);
1805 }
1806 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001807
1808 EmitBlock(Continue.getBlock());
1809 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001810 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001811 // Emit "LB = LB + Stride", "UB = UB + Stride".
1812 EmitIgnoredExpr(S.getNextLowerBound());
1813 EmitIgnoredExpr(S.getNextUpperBound());
1814 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001815
1816 EmitBranch(CondBlock);
1817 LoopStack.pop();
1818 // Emit the fall-through block.
1819 EmitBlock(LoopExit.getBlock());
1820
1821 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001822 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1823 if (!DynamicOrOrdered)
1824 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1825 };
1826 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001827}
1828
1829void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001830 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001831 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1832 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1833 auto &RT = CGM.getOpenMPRuntime();
1834
1835 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001836 const bool DynamicOrOrdered =
1837 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001838
1839 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001840 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1841 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001842 "static non-chunked schedule does not need outer loop");
1843
1844 // Emit outer loop.
1845 //
1846 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1847 // When schedule(dynamic,chunk_size) is specified, the iterations are
1848 // distributed to threads in the team in chunks as the threads request them.
1849 // Each thread executes a chunk of iterations, then requests another chunk,
1850 // until no chunks remain to be distributed. Each chunk contains chunk_size
1851 // iterations, except for the last chunk to be distributed, which may have
1852 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1853 //
1854 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1855 // to threads in the team in chunks as the executing threads request them.
1856 // Each thread executes a chunk of iterations, then requests another chunk,
1857 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1858 // each chunk is proportional to the number of unassigned iterations divided
1859 // by the number of threads in the team, decreasing to 1. For a chunk_size
1860 // with value k (greater than 1), the size of each chunk is determined in the
1861 // same way, with the restriction that the chunks do not contain fewer than k
1862 // iterations (except for the last chunk to be assigned, which may have fewer
1863 // than k iterations).
1864 //
1865 // When schedule(auto) is specified, the decision regarding scheduling is
1866 // delegated to the compiler and/or runtime system. The programmer gives the
1867 // implementation the freedom to choose any possible mapping of iterations to
1868 // threads in the team.
1869 //
1870 // When schedule(runtime) is specified, the decision regarding scheduling is
1871 // deferred until run time, and the schedule and chunk size are taken from the
1872 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1873 // implementation defined
1874 //
1875 // while(__kmpc_dispatch_next(&LB, &UB)) {
1876 // idx = LB;
1877 // while (idx <= UB) { BODY; ++idx;
1878 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1879 // } // inner loop
1880 // }
1881 //
1882 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1883 // When schedule(static, chunk_size) is specified, iterations are divided into
1884 // chunks of size chunk_size, and the chunks are assigned to the threads in
1885 // the team in a round-robin fashion in the order of the thread number.
1886 //
1887 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1888 // while (idx <= UB) { BODY; ++idx; } // inner loop
1889 // LB = LB + ST;
1890 // UB = UB + ST;
1891 // }
1892 //
1893
1894 const Expr *IVExpr = S.getIterationVariable();
1895 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1896 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1897
1898 if (DynamicOrOrdered) {
1899 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001900 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1901 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001902 } else {
1903 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1904 Ordered, IL, LB, UB, ST, Chunk);
1905 }
1906
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001907 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001908 ST, IL, Chunk);
1909}
1910
1911void CodeGenFunction::EmitOMPDistributeOuterLoop(
1912 OpenMPDistScheduleClauseKind ScheduleKind,
1913 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1914 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1915
1916 auto &RT = CGM.getOpenMPRuntime();
1917
1918 // Emit outer loop.
1919 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1920 // dynamic
1921 //
1922
1923 const Expr *IVExpr = S.getIterationVariable();
1924 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1925 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1926
1927 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1928 IVSize, IVSigned, /* Ordered = */ false,
1929 IL, LB, UB, ST, Chunk);
1930
1931 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1932 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001933}
1934
Carlo Bertolli9925f152016-06-27 14:55:37 +00001935void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1936 const OMPDistributeParallelForDirective &S) {
1937 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1938 CGM.getOpenMPRuntime().emitInlinedDirective(
1939 *this, OMPD_distribute_parallel_for,
1940 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1941 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev957d8562016-11-17 15:12:05 +00001942 OMPCancelStackRAII CancelRegion(CGF, OMPD_distribute_parallel_for,
1943 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001944 CGF.EmitStmt(
1945 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1946 });
1947}
1948
Kelvin Li4a39add2016-07-05 05:00:15 +00001949void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1950 const OMPDistributeParallelForSimdDirective &S) {
1951 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1952 CGM.getOpenMPRuntime().emitInlinedDirective(
1953 *this, OMPD_distribute_parallel_for_simd,
1954 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1955 OMPLoopScope PreInitScope(CGF, S);
1956 CGF.EmitStmt(
1957 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1958 });
1959}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001960
1961void CodeGenFunction::EmitOMPDistributeSimdDirective(
1962 const OMPDistributeSimdDirective &S) {
1963 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1964 CGM.getOpenMPRuntime().emitInlinedDirective(
1965 *this, OMPD_distribute_simd,
1966 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1967 OMPLoopScope PreInitScope(CGF, S);
1968 CGF.EmitStmt(
1969 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1970 });
1971}
1972
Kelvin Lia579b912016-07-14 02:54:56 +00001973void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1974 const OMPTargetParallelForSimdDirective &S) {
1975 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1976 CGM.getOpenMPRuntime().emitInlinedDirective(
1977 *this, OMPD_target_parallel_for_simd,
1978 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1979 OMPLoopScope PreInitScope(CGF, S);
1980 CGF.EmitStmt(
1981 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1982 });
1983}
1984
Kelvin Li986330c2016-07-20 22:57:10 +00001985void CodeGenFunction::EmitOMPTargetSimdDirective(
1986 const OMPTargetSimdDirective &S) {
1987 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1988 CGM.getOpenMPRuntime().emitInlinedDirective(
1989 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1990 OMPLoopScope PreInitScope(CGF, S);
1991 CGF.EmitStmt(
1992 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1993 });
1994}
1995
Kelvin Li02532872016-08-05 14:37:37 +00001996void CodeGenFunction::EmitOMPTeamsDistributeDirective(
1997 const OMPTeamsDistributeDirective &S) {
1998 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1999 CGM.getOpenMPRuntime().emitInlinedDirective(
2000 *this, OMPD_teams_distribute,
2001 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2002 OMPLoopScope PreInitScope(CGF, S);
2003 CGF.EmitStmt(
2004 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2005 });
2006}
2007
Kelvin Li4e325f72016-10-25 12:50:55 +00002008void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2009 const OMPTeamsDistributeSimdDirective &S) {
2010 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2011 CGM.getOpenMPRuntime().emitInlinedDirective(
2012 *this, OMPD_teams_distribute_simd,
2013 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2014 OMPLoopScope PreInitScope(CGF, S);
2015 CGF.EmitStmt(
2016 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2017 });
2018}
2019
Kelvin Li579e41c2016-11-30 23:51:03 +00002020void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2021 const OMPTeamsDistributeParallelForSimdDirective &S) {
2022 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2023 CGM.getOpenMPRuntime().emitInlinedDirective(
2024 *this, OMPD_teams_distribute_parallel_for_simd,
2025 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2026 OMPLoopScope PreInitScope(CGF, S);
2027 CGF.EmitStmt(
2028 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2029 });
2030}
Kelvin Li4e325f72016-10-25 12:50:55 +00002031
Kelvin Li7ade93f2016-12-09 03:24:30 +00002032void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2033 const OMPTeamsDistributeParallelForDirective &S) {
2034 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2035 CGM.getOpenMPRuntime().emitInlinedDirective(
2036 *this, OMPD_teams_distribute_parallel_for,
2037 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2038 OMPLoopScope PreInitScope(CGF, S);
2039 CGF.EmitStmt(
2040 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2041 });
2042}
2043
Kelvin Li83c451e2016-12-25 04:52:54 +00002044void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2045 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002046 CGM.getOpenMPRuntime().emitInlinedDirective(
2047 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002048 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002049 CGF.EmitStmt(
2050 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002051 });
2052}
2053
Kelvin Li80e8f562016-12-29 22:16:30 +00002054void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2055 const OMPTargetTeamsDistributeParallelForDirective &S) {
2056 CGM.getOpenMPRuntime().emitInlinedDirective(
2057 *this, OMPD_target_teams_distribute_parallel_for,
2058 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2059 CGF.EmitStmt(
2060 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2061 });
2062}
2063
Kelvin Li1851df52017-01-03 05:23:48 +00002064void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2065 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2066 CGM.getOpenMPRuntime().emitInlinedDirective(
2067 *this, OMPD_target_teams_distribute_parallel_for_simd,
2068 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2069 CGF.EmitStmt(
2070 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2071 });
2072}
2073
Kelvin Lida681182017-01-10 18:08:18 +00002074void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2075 const OMPTargetTeamsDistributeSimdDirective &S) {
2076 CGM.getOpenMPRuntime().emitInlinedDirective(
2077 *this, OMPD_target_teams_distribute_simd,
2078 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2079 CGF.EmitStmt(
2080 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2081 });
2082}
2083
Alexander Musmanc6388682014-12-15 07:07:06 +00002084/// \brief Emit a helper variable and return corresponding lvalue.
2085static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2086 const DeclRefExpr *Helper) {
2087 auto VDecl = cast<VarDecl>(Helper->getDecl());
2088 CGF.EmitVarDecl(*VDecl);
2089 return CGF.EmitLValue(Helper);
2090}
2091
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002092namespace {
2093 struct ScheduleKindModifiersTy {
2094 OpenMPScheduleClauseKind Kind;
2095 OpenMPScheduleClauseModifier M1;
2096 OpenMPScheduleClauseModifier M2;
2097 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2098 OpenMPScheduleClauseModifier M1,
2099 OpenMPScheduleClauseModifier M2)
2100 : Kind(Kind), M1(M1), M2(M2) {}
2101 };
2102} // namespace
2103
Alexey Bataev38e89532015-04-16 04:54:05 +00002104bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
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.
2154 LValue LB =
2155 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2156 LValue UB =
2157 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2158 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.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002243 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002244 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2245 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002246 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002247 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2248 EmitOMPSimdFinal(S,
2249 [&](CodeGenFunction &CGF) -> llvm::Value * {
2250 return CGF.Builder.CreateIsNotNull(
2251 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2252 });
2253 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002254 EmitOMPReductionClauseFinal(
2255 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2256 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2257 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002258 // Emit post-update of the reduction variables if IsLastIter != 0.
2259 emitPostUpdateForReductionClause(
2260 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2261 return CGF.Builder.CreateIsNotNull(
2262 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2263 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002264 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2265 if (HasLastprivateClause)
2266 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002267 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2268 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002269 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002270 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002271 return CGF.Builder.CreateIsNotNull(
2272 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2273 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002274 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002275 if (ContBlock) {
2276 EmitBranch(ContBlock);
2277 EmitBlock(ContBlock, true);
2278 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002279 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002280 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002281}
2282
2283void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002284 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002285 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2286 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002287 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002288 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2289 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002290 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002291 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002292 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2293 S.hasCancel());
2294 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002295
2296 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002297 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002298 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2299 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002300}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002301
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002302void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002303 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002304 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2305 PrePostActionTy &) {
2306 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2307 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002308 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002309 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002310 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2311 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002312
2313 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002314 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002315 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2316 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002317}
2318
Alexey Bataev2df54a02015-03-12 08:53:29 +00002319static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2320 const Twine &Name,
2321 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002322 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002323 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002324 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002325 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002326}
2327
Alexey Bataev3392d762016-02-16 11:18:12 +00002328void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002329 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2330 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002331 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002332 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2333 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002334 auto &C = CGF.CGM.getContext();
2335 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2336 // Emit helper vars inits.
2337 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2338 CGF.Builder.getInt32(0));
2339 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2340 : CGF.Builder.getInt32(0);
2341 LValue UB =
2342 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2343 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2344 CGF.Builder.getInt32(1));
2345 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2346 CGF.Builder.getInt32(0));
2347 // Loop counter.
2348 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2349 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2350 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2351 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2352 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2353 // Generate condition for loop.
2354 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002355 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002356 // Increment for loop counter.
2357 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2358 S.getLocStart());
2359 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2360 // Iterate through all sections and emit a switch construct:
2361 // switch (IV) {
2362 // case 0:
2363 // <SectionStmt[0]>;
2364 // break;
2365 // ...
2366 // case <NumSection> - 1:
2367 // <SectionStmt[<NumSection> - 1]>;
2368 // break;
2369 // }
2370 // .omp.sections.exit:
2371 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2372 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2373 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2374 CS == nullptr ? 1 : CS->size());
2375 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002376 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002377 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002378 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2379 CGF.EmitBlock(CaseBB);
2380 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002381 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002382 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002383 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002384 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002385 } else {
2386 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2387 CGF.EmitBlock(CaseBB);
2388 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2389 CGF.EmitStmt(Stmt);
2390 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002391 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002392 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002393 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002394
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002395 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2396 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002397 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002398 // initialization of firstprivate variables and post-update of lastprivate
2399 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002400 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2401 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2402 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002403 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002404 CGF.EmitOMPPrivateClause(S, LoopScope);
2405 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2406 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2407 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002408
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002409 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002410 OpenMPScheduleTy ScheduleKind;
2411 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002412 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002413 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002414 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2415 UB.getAddress(), ST.getAddress());
2416 // UB = min(UB, GlobalUB);
2417 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2418 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2419 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2420 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2421 // IV = LB;
2422 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2423 // while (idx <= UB) { BODY; ++idx; }
2424 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2425 [](CodeGenFunction &) {});
2426 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002427 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2428 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2429 };
2430 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002431 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002432 // Emit post-update of the reduction variables if IsLastIter != 0.
2433 emitPostUpdateForReductionClause(
2434 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2435 return CGF.Builder.CreateIsNotNull(
2436 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2437 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002438
2439 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2440 if (HasLastprivates)
2441 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002442 S, /*NoFinals=*/false,
2443 CGF.Builder.CreateIsNotNull(
2444 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002445 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002446
2447 bool HasCancel = false;
2448 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2449 HasCancel = OSD->hasCancel();
2450 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2451 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002452 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002453 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2454 HasCancel);
2455 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2456 // clause. Otherwise the barrier will be generated by the codegen for the
2457 // directive.
2458 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002459 // Emit implicit barrier to synchronize threads and avoid data races on
2460 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002461 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2462 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002463 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002464}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002465
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002466void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002467 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002468 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002469 EmitSections(S);
2470 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002471 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002472 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002473 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2474 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002475 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002476}
2477
2478void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002480 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002481 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002482 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002483 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2484 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002485}
2486
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002487void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002488 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002489 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002490 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002491 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002492 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002493 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002494 // Build a list of copyprivate variables along with helper expressions
2495 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002496 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002497 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002498 DestExprs.append(C->destination_exprs().begin(),
2499 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002500 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002501 AssignmentOps.append(C->assignment_ops().begin(),
2502 C->assignment_ops().end());
2503 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002504 // Emit code for 'single' region along with 'copyprivate' clauses
2505 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2506 Action.Enter(CGF);
2507 OMPPrivateScope SingleScope(CGF);
2508 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2509 CGF.EmitOMPPrivateClause(S, SingleScope);
2510 (void)SingleScope.Privatize();
2511 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2512 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002513 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002514 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002515 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2516 CopyprivateVars, DestExprs,
2517 SrcExprs, AssignmentOps);
2518 }
2519 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2520 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002521 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002522 CGM.getOpenMPRuntime().emitBarrierCall(
2523 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002524 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002525 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002526}
2527
Alexey Bataev8d690652014-12-04 07:23:53 +00002528void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002529 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2530 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002531 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002532 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002533 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002534 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002535}
2536
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002537void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002538 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2539 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002540 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002541 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002542 Expr *Hint = nullptr;
2543 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2544 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002545 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002546 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2547 S.getDirectiveName().getAsString(),
2548 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002549}
2550
Alexey Bataev671605e2015-04-13 05:28:11 +00002551void CodeGenFunction::EmitOMPParallelForDirective(
2552 const OMPParallelForDirective &S) {
2553 // Emit directive as a combined directive that consists of two implicit
2554 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002555 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002556 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Alexey Bataev671605e2015-04-13 05:28:11 +00002557 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002558 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002559 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002560}
2561
Alexander Musmane4e893b2014-09-23 09:33:00 +00002562void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002563 const OMPParallelForSimdDirective &S) {
2564 // Emit directive as a combined directive that consists of two implicit
2565 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002566 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002567 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002568 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002569 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002570}
2571
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002572void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002573 const OMPParallelSectionsDirective &S) {
2574 // Emit directive as a combined directive that consists of two implicit
2575 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002576 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2577 CGF.EmitSections(S);
2578 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002579 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002580}
2581
Alexey Bataev7292c292016-04-25 12:22:29 +00002582void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2583 const RegionCodeGenTy &BodyGen,
2584 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002585 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002586 // Emit outlined function for task construct.
2587 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002588 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002589 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002590 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002591 // Check if the task is final
2592 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2593 // If the condition constant folds and can be elided, try to avoid emitting
2594 // the condition and the dead arm of the if/else.
2595 auto *Cond = Clause->getCondition();
2596 bool CondConstant;
2597 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2598 Data.Final.setInt(CondConstant);
2599 else
2600 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2601 } else {
2602 // By default the task is not final.
2603 Data.Final.setInt(/*IntVal=*/false);
2604 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002605 // Check if the task has 'priority' clause.
2606 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002607 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002608 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002609 Data.Priority.setPointer(EmitScalarConversion(
2610 EmitScalarExpr(Prio), Prio->getType(),
2611 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2612 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002613 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002614 // The first function argument for tasks is a thread id, the second one is a
2615 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002616 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2617 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002618 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002619 auto IRef = C->varlist_begin();
2620 for (auto *IInit : C->private_copies()) {
2621 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2622 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002623 Data.PrivateVars.push_back(*IRef);
2624 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002625 }
2626 ++IRef;
2627 }
2628 }
2629 EmittedAsPrivate.clear();
2630 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002631 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002632 auto IRef = C->varlist_begin();
2633 auto IElemInitRef = C->inits().begin();
2634 for (auto *IInit : C->private_copies()) {
2635 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2636 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002637 Data.FirstprivateVars.push_back(*IRef);
2638 Data.FirstprivateCopies.push_back(IInit);
2639 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002640 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002641 ++IRef;
2642 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002643 }
2644 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002645 // Get list of lastprivate variables (for taskloops).
2646 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2647 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2648 auto IRef = C->varlist_begin();
2649 auto ID = C->destination_exprs().begin();
2650 for (auto *IInit : C->private_copies()) {
2651 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2652 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2653 Data.LastprivateVars.push_back(*IRef);
2654 Data.LastprivateCopies.push_back(IInit);
2655 }
2656 LastprivateDstsOrigs.insert(
2657 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2658 cast<DeclRefExpr>(*IRef)});
2659 ++IRef;
2660 ++ID;
2661 }
2662 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002663 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002664 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2665 for (auto *IRef : C->varlists())
2666 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00002667 auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002668 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002669 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002670 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002671 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2672 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002673 auto *CopyFn = CGF.Builder.CreateLoad(
2674 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2675 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2676 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2677 // Map privates.
2678 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2679 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2680 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002681 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002682 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2683 Address PrivatePtr = CGF.CreateMemTemp(
2684 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2685 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2686 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002687 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002688 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002689 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2690 Address PrivatePtr =
2691 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2692 ".firstpriv.ptr.addr");
2693 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2694 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002695 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002696 for (auto *E : Data.LastprivateVars) {
2697 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2698 Address PrivatePtr =
2699 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2700 ".lastpriv.ptr.addr");
2701 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2702 CallArgs.push_back(PrivatePtr.getPointer());
2703 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002704 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002705 for (auto &&Pair : LastprivateDstsOrigs) {
2706 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2707 DeclRefExpr DRE(
2708 const_cast<VarDecl *>(OrigVD),
2709 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2710 OrigVD) != nullptr,
2711 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2712 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2713 return CGF.EmitLValue(&DRE).getAddress();
2714 });
2715 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002716 for (auto &&Pair : PrivatePtrs) {
2717 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2718 CGF.getContext().getDeclAlign(Pair.first));
2719 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2720 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002721 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002722 (void)Scope.Privatize();
2723
2724 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002725 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002726 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002727 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2728 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2729 Data.NumberOfParts);
2730 OMPLexicalScope Scope(*this, S);
2731 TaskGen(*this, OutlinedFn, Data);
2732}
2733
2734void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2735 // Emit outlined function for task construct.
2736 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2737 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002738 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002739 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002740 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2741 if (C->getNameModifier() == OMPD_unknown ||
2742 C->getNameModifier() == OMPD_task) {
2743 IfCond = C->getCondition();
2744 break;
2745 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002746 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002747
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002748 OMPTaskDataTy Data;
2749 // Check if we should emit tied or untied task.
2750 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002751 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2752 CGF.EmitStmt(CS->getCapturedStmt());
2753 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002754 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002755 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002756 const OMPTaskDataTy &Data) {
2757 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2758 SharedsTy, CapturedStruct, IfCond,
2759 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002760 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002761 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002762}
2763
Alexey Bataev9f797f32015-02-05 05:57:51 +00002764void CodeGenFunction::EmitOMPTaskyieldDirective(
2765 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002766 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002767}
2768
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002769void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002770 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002771}
2772
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002773void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2774 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002775}
2776
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002777void CodeGenFunction::EmitOMPTaskgroupDirective(
2778 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002779 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2780 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002781 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002782 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002783 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002784 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2785}
2786
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002787void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002788 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002789 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002790 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2791 FlushClause->varlist_end());
2792 }
2793 return llvm::None;
2794 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002795}
2796
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002797void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2798 // Emit the loop iteration variable.
2799 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2800 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2801 EmitVarDecl(*IVDecl);
2802
2803 // Emit the iterations count variable.
2804 // If it is not a variable, Sema decided to calculate iterations count on each
2805 // iteration (e.g., it is foldable into a constant).
2806 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2807 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2808 // Emit calculation of the iterations count.
2809 EmitIgnoredExpr(S.getCalcLastIteration());
2810 }
2811
2812 auto &RT = CGM.getOpenMPRuntime();
2813
Carlo Bertolli962bb802017-01-03 18:24:42 +00002814 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002815 // Check pre-condition.
2816 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002817 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002818 // Skip the entire loop if we don't meet the precondition.
2819 // If the condition constant folds and can be elided, avoid emitting the
2820 // whole loop.
2821 bool CondConstant;
2822 llvm::BasicBlock *ContBlock = nullptr;
2823 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2824 if (!CondConstant)
2825 return;
2826 } else {
2827 auto *ThenBlock = createBasicBlock("omp.precond.then");
2828 ContBlock = createBasicBlock("omp.precond.end");
2829 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2830 getProfileCount(&S));
2831 EmitBlock(ThenBlock);
2832 incrementProfileCounter(&S);
2833 }
2834
2835 // Emit 'then' code.
2836 {
2837 // Emit helper vars inits.
2838 LValue LB =
2839 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2840 LValue UB =
2841 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2842 LValue ST =
2843 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2844 LValue IL =
2845 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2846
2847 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00002848 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2849 // Emit implicit barrier to synchronize threads and avoid data races on
2850 // initialization of firstprivate variables and post-update of
2851 // lastprivate variables.
2852 CGM.getOpenMPRuntime().emitBarrierCall(
2853 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2854 /*ForceSimpleCall=*/true);
2855 }
2856 EmitOMPPrivateClause(S, LoopScope);
2857 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002858 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002859 (void)LoopScope.Privatize();
2860
2861 // Detect the distribute schedule kind and chunk.
2862 llvm::Value *Chunk = nullptr;
2863 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2864 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2865 ScheduleKind = C->getDistScheduleKind();
2866 if (const auto *Ch = C->getChunkSize()) {
2867 Chunk = EmitScalarExpr(Ch);
2868 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2869 S.getIterationVariable()->getType(),
2870 S.getLocStart());
2871 }
2872 }
2873 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2874 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2875
2876 // OpenMP [2.10.8, distribute Construct, Description]
2877 // If dist_schedule is specified, kind must be static. If specified,
2878 // iterations are divided into chunks of size chunk_size, chunks are
2879 // assigned to the teams of the league in a round-robin fashion in the
2880 // order of the team number. When no chunk_size is specified, the
2881 // iteration space is divided into chunks that are approximately equal
2882 // in size, and at most one chunk is distributed to each team of the
2883 // league. The size of the chunks is unspecified in this case.
2884 if (RT.isStaticNonchunked(ScheduleKind,
2885 /* Chunked */ Chunk != nullptr)) {
2886 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2887 IVSize, IVSigned, /* Ordered = */ false,
2888 IL.getAddress(), LB.getAddress(),
2889 UB.getAddress(), ST.getAddress());
2890 auto LoopExit =
2891 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2892 // UB = min(UB, GlobalUB);
2893 EmitIgnoredExpr(S.getEnsureUpperBound());
2894 // IV = LB;
2895 EmitIgnoredExpr(S.getInit());
2896 // while (idx <= UB) { BODY; ++idx; }
2897 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2898 S.getInc(),
2899 [&S, LoopExit](CodeGenFunction &CGF) {
2900 CGF.EmitOMPLoopBody(S, LoopExit);
2901 CGF.EmitStopPoint(&S);
2902 },
2903 [](CodeGenFunction &) {});
2904 EmitBlock(LoopExit.getBlock());
2905 // Tell the runtime we are done.
2906 RT.emitForStaticFinish(*this, S.getLocStart());
2907 } else {
2908 // Emit the outer loop, which requests its work chunk [LB..UB] from
2909 // runtime and runs the inner loop to process it.
2910 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2911 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2912 IL.getAddress(), Chunk);
2913 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00002914
2915 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2916 if (HasLastprivateClause)
2917 EmitOMPLastprivateClauseFinal(
2918 S, /*NoFinals=*/false,
2919 Builder.CreateIsNotNull(
2920 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002921 }
2922
2923 // We're now done with the loop, so jump to the continuation block.
2924 if (ContBlock) {
2925 EmitBranch(ContBlock);
2926 EmitBlock(ContBlock, true);
2927 }
2928 }
2929}
2930
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002931void CodeGenFunction::EmitOMPDistributeDirective(
2932 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002933 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002934 CGF.EmitOMPDistributeLoop(S);
2935 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002936 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002937 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2938 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002939}
2940
Alexey Bataev5f600d62015-09-29 03:48:57 +00002941static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2942 const CapturedStmt *S) {
2943 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2944 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2945 CGF.CapturedStmtInfo = &CapStmtInfo;
2946 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2947 Fn->addFnAttr(llvm::Attribute::NoInline);
2948 return Fn;
2949}
2950
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002951void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002952 if (!S.getAssociatedStmt()) {
2953 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
2954 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00002955 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00002956 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002957 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002958 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2959 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002960 if (C) {
2961 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2962 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2963 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2964 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2965 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2966 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002967 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002968 CGF.EmitStmt(
2969 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2970 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002971 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002972 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002973 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002974}
2975
Alexey Bataevb57056f2015-01-22 06:17:56 +00002976static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002977 QualType SrcType, QualType DestType,
2978 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002979 assert(CGF.hasScalarEvaluationKind(DestType) &&
2980 "DestType must have scalar evaluation kind.");
2981 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2982 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002983 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2984 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002985 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002986 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002987}
2988
2989static CodeGenFunction::ComplexPairTy
2990convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002991 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002992 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2993 "DestType must have complex evaluation kind.");
2994 CodeGenFunction::ComplexPairTy ComplexVal;
2995 if (Val.isScalar()) {
2996 // Convert the input element to the element type of the complex.
2997 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002998 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2999 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003000 ComplexVal = CodeGenFunction::ComplexPairTy(
3001 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3002 } else {
3003 assert(Val.isComplex() && "Must be a scalar or complex.");
3004 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3005 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3006 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003007 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003008 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003009 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003010 }
3011 return ComplexVal;
3012}
3013
Alexey Bataev5e018f92015-04-23 06:35:10 +00003014static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3015 LValue LVal, RValue RVal) {
3016 if (LVal.isGlobalReg()) {
3017 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3018 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003019 CGF.EmitAtomicStore(RVal, LVal,
3020 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3021 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003022 LVal.isVolatile(), /*IsInit=*/false);
3023 }
3024}
3025
Alexey Bataev8524d152016-01-21 12:35:58 +00003026void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3027 QualType RValTy, SourceLocation Loc) {
3028 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003029 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003030 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3031 *this, RVal, RValTy, LVal.getType(), Loc)),
3032 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003033 break;
3034 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003035 EmitStoreOfComplex(
3036 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003037 /*isInit=*/false);
3038 break;
3039 case TEK_Aggregate:
3040 llvm_unreachable("Must be a scalar or complex.");
3041 }
3042}
3043
Alexey Bataevb57056f2015-01-22 06:17:56 +00003044static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3045 const Expr *X, const Expr *V,
3046 SourceLocation Loc) {
3047 // v = x;
3048 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3049 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3050 LValue XLValue = CGF.EmitLValue(X);
3051 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003052 RValue Res = XLValue.isGlobalReg()
3053 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003054 : CGF.EmitAtomicLoad(
3055 XLValue, Loc,
3056 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3057 : llvm::AtomicOrdering::Monotonic,
3058 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003059 // OpenMP, 2.12.6, atomic Construct
3060 // Any atomic construct with a seq_cst clause forces the atomically
3061 // performed operation to include an implicit flush operation without a
3062 // list.
3063 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003064 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003065 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003066}
3067
Alexey Bataevb8329262015-02-27 06:33:30 +00003068static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3069 const Expr *X, const Expr *E,
3070 SourceLocation Loc) {
3071 // x = expr;
3072 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003073 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003074 // OpenMP, 2.12.6, atomic Construct
3075 // Any atomic construct with a seq_cst clause forces the atomically
3076 // performed operation to include an implicit flush operation without a
3077 // list.
3078 if (IsSeqCst)
3079 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3080}
3081
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003082static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3083 RValue Update,
3084 BinaryOperatorKind BO,
3085 llvm::AtomicOrdering AO,
3086 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003087 auto &Context = CGF.CGM.getContext();
3088 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003089 // expression is simple and atomic is allowed for the given type for the
3090 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003091 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003092 !Update.getScalarVal()->getType()->isIntegerTy() ||
3093 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3094 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003095 X.getAddress().getElementType())) ||
3096 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003097 !Context.getTargetInfo().hasBuiltinAtomic(
3098 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003099 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003100
3101 llvm::AtomicRMWInst::BinOp RMWOp;
3102 switch (BO) {
3103 case BO_Add:
3104 RMWOp = llvm::AtomicRMWInst::Add;
3105 break;
3106 case BO_Sub:
3107 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003108 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003109 RMWOp = llvm::AtomicRMWInst::Sub;
3110 break;
3111 case BO_And:
3112 RMWOp = llvm::AtomicRMWInst::And;
3113 break;
3114 case BO_Or:
3115 RMWOp = llvm::AtomicRMWInst::Or;
3116 break;
3117 case BO_Xor:
3118 RMWOp = llvm::AtomicRMWInst::Xor;
3119 break;
3120 case BO_LT:
3121 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3122 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3123 : llvm::AtomicRMWInst::Max)
3124 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3125 : llvm::AtomicRMWInst::UMax);
3126 break;
3127 case BO_GT:
3128 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3129 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3130 : llvm::AtomicRMWInst::Min)
3131 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3132 : llvm::AtomicRMWInst::UMin);
3133 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003134 case BO_Assign:
3135 RMWOp = llvm::AtomicRMWInst::Xchg;
3136 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003137 case BO_Mul:
3138 case BO_Div:
3139 case BO_Rem:
3140 case BO_Shl:
3141 case BO_Shr:
3142 case BO_LAnd:
3143 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003144 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003145 case BO_PtrMemD:
3146 case BO_PtrMemI:
3147 case BO_LE:
3148 case BO_GE:
3149 case BO_EQ:
3150 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003151 case BO_AddAssign:
3152 case BO_SubAssign:
3153 case BO_AndAssign:
3154 case BO_OrAssign:
3155 case BO_XorAssign:
3156 case BO_MulAssign:
3157 case BO_DivAssign:
3158 case BO_RemAssign:
3159 case BO_ShlAssign:
3160 case BO_ShrAssign:
3161 case BO_Comma:
3162 llvm_unreachable("Unsupported atomic update operation");
3163 }
3164 auto *UpdateVal = Update.getScalarVal();
3165 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3166 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003167 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003168 X.getType()->hasSignedIntegerRepresentation());
3169 }
John McCall7f416cc2015-09-08 08:05:57 +00003170 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003171 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003172}
3173
Alexey Bataev5e018f92015-04-23 06:35:10 +00003174std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003175 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3176 llvm::AtomicOrdering AO, SourceLocation Loc,
3177 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3178 // Update expressions are allowed to have the following forms:
3179 // x binop= expr; -> xrval + expr;
3180 // x++, ++x -> xrval + 1;
3181 // x--, --x -> xrval - 1;
3182 // x = x binop expr; -> xrval binop expr
3183 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003184 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3185 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003186 if (X.isGlobalReg()) {
3187 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3188 // 'xrval'.
3189 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3190 } else {
3191 // Perform compare-and-swap procedure.
3192 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003193 }
3194 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003195 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003196}
3197
3198static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3199 const Expr *X, const Expr *E,
3200 const Expr *UE, bool IsXLHSInRHSPart,
3201 SourceLocation Loc) {
3202 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3203 "Update expr in 'atomic update' must be a binary operator.");
3204 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3205 // Update expressions are allowed to have the following forms:
3206 // x binop= expr; -> xrval + expr;
3207 // x++, ++x -> xrval + 1;
3208 // x--, --x -> xrval - 1;
3209 // x = x binop expr; -> xrval binop expr
3210 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003211 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003212 LValue XLValue = CGF.EmitLValue(X);
3213 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003214 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3215 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003216 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3217 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3218 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3219 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3220 auto Gen =
3221 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3222 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3223 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3224 return CGF.EmitAnyExpr(UE);
3225 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003226 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3227 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3228 // OpenMP, 2.12.6, atomic Construct
3229 // Any atomic construct with a seq_cst clause forces the atomically
3230 // performed operation to include an implicit flush operation without a
3231 // list.
3232 if (IsSeqCst)
3233 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3234}
3235
3236static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003237 QualType SourceType, QualType ResType,
3238 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003239 switch (CGF.getEvaluationKind(ResType)) {
3240 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003241 return RValue::get(
3242 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003243 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003244 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003245 return RValue::getComplex(Res.first, Res.second);
3246 }
3247 case TEK_Aggregate:
3248 break;
3249 }
3250 llvm_unreachable("Must be a scalar or complex.");
3251}
3252
3253static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3254 bool IsPostfixUpdate, const Expr *V,
3255 const Expr *X, const Expr *E,
3256 const Expr *UE, bool IsXLHSInRHSPart,
3257 SourceLocation Loc) {
3258 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3259 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3260 RValue NewVVal;
3261 LValue VLValue = CGF.EmitLValue(V);
3262 LValue XLValue = CGF.EmitLValue(X);
3263 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003264 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3265 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003266 QualType NewVValType;
3267 if (UE) {
3268 // 'x' is updated with some additional value.
3269 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3270 "Update expr in 'atomic capture' must be a binary operator.");
3271 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3272 // Update expressions are allowed to have the following forms:
3273 // x binop= expr; -> xrval + expr;
3274 // x++, ++x -> xrval + 1;
3275 // x--, --x -> xrval - 1;
3276 // x = x binop expr; -> xrval binop expr
3277 // x = expr Op x; - > expr binop xrval;
3278 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3279 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3280 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3281 NewVValType = XRValExpr->getType();
3282 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3283 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003284 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003285 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3286 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3287 RValue Res = CGF.EmitAnyExpr(UE);
3288 NewVVal = IsPostfixUpdate ? XRValue : Res;
3289 return Res;
3290 };
3291 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3292 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3293 if (Res.first) {
3294 // 'atomicrmw' instruction was generated.
3295 if (IsPostfixUpdate) {
3296 // Use old value from 'atomicrmw'.
3297 NewVVal = Res.second;
3298 } else {
3299 // 'atomicrmw' does not provide new value, so evaluate it using old
3300 // value of 'x'.
3301 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3302 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3303 NewVVal = CGF.EmitAnyExpr(UE);
3304 }
3305 }
3306 } else {
3307 // 'x' is simply rewritten with some 'expr'.
3308 NewVValType = X->getType().getNonReferenceType();
3309 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003310 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003311 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003312 NewVVal = XRValue;
3313 return ExprRValue;
3314 };
3315 // Try to perform atomicrmw xchg, otherwise simple exchange.
3316 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3317 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3318 Loc, Gen);
3319 if (Res.first) {
3320 // 'atomicrmw' instruction was generated.
3321 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3322 }
3323 }
3324 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003325 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003326 // OpenMP, 2.12.6, atomic Construct
3327 // Any atomic construct with a seq_cst clause forces the atomically
3328 // performed operation to include an implicit flush operation without a
3329 // list.
3330 if (IsSeqCst)
3331 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3332}
3333
Alexey Bataevb57056f2015-01-22 06:17:56 +00003334static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003335 bool IsSeqCst, bool IsPostfixUpdate,
3336 const Expr *X, const Expr *V, const Expr *E,
3337 const Expr *UE, bool IsXLHSInRHSPart,
3338 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003339 switch (Kind) {
3340 case OMPC_read:
3341 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3342 break;
3343 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003344 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3345 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003346 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003347 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003348 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3349 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003350 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003351 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3352 IsXLHSInRHSPart, Loc);
3353 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003354 case OMPC_if:
3355 case OMPC_final:
3356 case OMPC_num_threads:
3357 case OMPC_private:
3358 case OMPC_firstprivate:
3359 case OMPC_lastprivate:
3360 case OMPC_reduction:
3361 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003362 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003363 case OMPC_collapse:
3364 case OMPC_default:
3365 case OMPC_seq_cst:
3366 case OMPC_shared:
3367 case OMPC_linear:
3368 case OMPC_aligned:
3369 case OMPC_copyin:
3370 case OMPC_copyprivate:
3371 case OMPC_flush:
3372 case OMPC_proc_bind:
3373 case OMPC_schedule:
3374 case OMPC_ordered:
3375 case OMPC_nowait:
3376 case OMPC_untied:
3377 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003378 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003379 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003380 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003381 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003382 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003383 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003384 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003385 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003386 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003387 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003388 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003389 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003390 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003391 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003392 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003393 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003394 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003395 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003396 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003397 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003398 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3399 }
3400}
3401
3402void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003403 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003404 OpenMPClauseKind Kind = OMPC_unknown;
3405 for (auto *C : S.clauses()) {
3406 // Find first clause (skip seq_cst clause, if it is first).
3407 if (C->getClauseKind() != OMPC_seq_cst) {
3408 Kind = C->getClauseKind();
3409 break;
3410 }
3411 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003412
3413 const auto *CS =
3414 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003415 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003416 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003417 }
3418 // Processing for statements under 'atomic capture'.
3419 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3420 for (const auto *C : Compound->body()) {
3421 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3422 enterFullExpression(EWC);
3423 }
3424 }
3425 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003426
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003427 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3428 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003429 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003430 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3431 S.getV(), S.getExpr(), S.getUpdateExpr(),
3432 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003433 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003434 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003435 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003436}
3437
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003438static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3439 const OMPExecutableDirective &S,
3440 const RegionCodeGenTy &CodeGen) {
3441 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3442 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003443 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3444
Samuel Antaoee8fb302016-01-06 13:42:12 +00003445 llvm::Function *Fn = nullptr;
3446 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003447
Samuel Antaobed3c462015-10-02 16:14:20 +00003448 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003449 // Check for the at most one if clause associated with the target region.
3450 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3451 if (C->getNameModifier() == OMPD_unknown ||
3452 C->getNameModifier() == OMPD_target) {
3453 IfCond = C->getCondition();
3454 break;
3455 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003456 }
3457
3458 // Check if we have any device clause associated with the directive.
3459 const Expr *Device = nullptr;
3460 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3461 Device = C->getDevice();
3462 }
3463
Samuel Antaoee8fb302016-01-06 13:42:12 +00003464 // Check if we have an if clause whose conditional always evaluates to false
3465 // or if we do not have any targets specified. If so the target region is not
3466 // an offload entry point.
3467 bool IsOffloadEntry = true;
3468 if (IfCond) {
3469 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003470 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003471 IsOffloadEntry = false;
3472 }
3473 if (CGM.getLangOpts().OMPTargetTriples.empty())
3474 IsOffloadEntry = false;
3475
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003476 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003477 StringRef ParentName;
3478 // In case we have Ctors/Dtors we use the complete type variant to produce
3479 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003480 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003481 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003482 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003483 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3484 else
3485 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003486 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003487
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003488 // Emit target region as a standalone region.
3489 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3490 IsOffloadEntry, CodeGen);
3491 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003492 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3493 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003494 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003495 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003496}
3497
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003498static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3499 PrePostActionTy &Action) {
3500 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3501 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3502 CGF.EmitOMPPrivateClause(S, PrivateScope);
3503 (void)PrivateScope.Privatize();
3504
3505 Action.Enter(CGF);
3506 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3507}
3508
3509void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3510 StringRef ParentName,
3511 const OMPTargetDirective &S) {
3512 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3513 emitTargetRegion(CGF, S, Action);
3514 };
3515 llvm::Function *Fn;
3516 llvm::Constant *Addr;
3517 // Emit target region as a standalone region.
3518 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3519 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3520 assert(Fn && Addr && "Target device function emission failed.");
3521}
3522
3523void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3524 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3525 emitTargetRegion(CGF, S, Action);
3526 };
3527 emitCommonOMPTargetDirective(*this, S, CodeGen);
3528}
3529
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003530static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3531 const OMPExecutableDirective &S,
3532 OpenMPDirectiveKind InnermostKind,
3533 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003534 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3535 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3536 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003537
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003538 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3539 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003540 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003541 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3542 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003543
Carlo Bertollic6872252016-04-04 15:55:02 +00003544 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3545 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003546 }
3547
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003548 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003549 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3550 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003551 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3552 CapturedVars);
3553}
3554
3555void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003556 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003557 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003558 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003559 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3560 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003561 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003562 (void)PrivateScope.Privatize();
3563 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003564 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003565 };
3566 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003567 emitPostUpdateForReductionClause(
3568 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003569}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003570
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003571static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3572 const OMPTargetTeamsDirective &S) {
3573 auto *CS = S.getCapturedStmt(OMPD_teams);
3574 Action.Enter(CGF);
3575 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3576 // TODO: Add support for clauses.
3577 CGF.EmitStmt(CS->getCapturedStmt());
3578 };
3579 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3580}
3581
3582void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3583 CodeGenModule &CGM, StringRef ParentName,
3584 const OMPTargetTeamsDirective &S) {
3585 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3586 emitTargetTeamsRegion(CGF, Action, S);
3587 };
3588 llvm::Function *Fn;
3589 llvm::Constant *Addr;
3590 // Emit target region as a standalone region.
3591 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3592 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3593 assert(Fn && Addr && "Target device function emission failed.");
3594}
3595
3596void CodeGenFunction::EmitOMPTargetTeamsDirective(
3597 const OMPTargetTeamsDirective &S) {
3598 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3599 emitTargetTeamsRegion(CGF, Action, S);
3600 };
3601 emitCommonOMPTargetDirective(*this, S, CodeGen);
3602}
3603
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003604void CodeGenFunction::EmitOMPCancellationPointDirective(
3605 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003606 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3607 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003608}
3609
Alexey Bataev80909872015-07-02 11:25:17 +00003610void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003611 const Expr *IfCond = nullptr;
3612 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3613 if (C->getNameModifier() == OMPD_unknown ||
3614 C->getNameModifier() == OMPD_cancel) {
3615 IfCond = C->getCondition();
3616 break;
3617 }
3618 }
3619 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003620 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003621}
3622
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003623CodeGenFunction::JumpDest
3624CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003625 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3626 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003627 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003628 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003629 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3630 Kind == OMPD_distribute_parallel_for ||
3631 Kind == OMPD_target_parallel_for);
3632 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003633}
Michael Wong65f367f2015-07-21 13:44:28 +00003634
Samuel Antaocc10b852016-07-28 14:23:26 +00003635void CodeGenFunction::EmitOMPUseDevicePtrClause(
3636 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3637 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3638 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3639 auto OrigVarIt = C.varlist_begin();
3640 auto InitIt = C.inits().begin();
3641 for (auto PvtVarIt : C.private_copies()) {
3642 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3643 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3644 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3645
3646 // In order to identify the right initializer we need to match the
3647 // declaration used by the mapping logic. In some cases we may get
3648 // OMPCapturedExprDecl that refers to the original declaration.
3649 const ValueDecl *MatchingVD = OrigVD;
3650 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3651 // OMPCapturedExprDecl are used to privative fields of the current
3652 // structure.
3653 auto *ME = cast<MemberExpr>(OED->getInit());
3654 assert(isa<CXXThisExpr>(ME->getBase()) &&
3655 "Base should be the current struct!");
3656 MatchingVD = ME->getMemberDecl();
3657 }
3658
3659 // If we don't have information about the current list item, move on to
3660 // the next one.
3661 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3662 if (InitAddrIt == CaptureDeviceAddrMap.end())
3663 continue;
3664
3665 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3666 // Initialize the temporary initialization variable with the address we
3667 // get from the runtime library. We have to cast the source address
3668 // because it is always a void *. References are materialized in the
3669 // privatization scope, so the initialization here disregards the fact
3670 // the original variable is a reference.
3671 QualType AddrQTy =
3672 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3673 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3674 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3675 setAddrOfLocalVar(InitVD, InitAddr);
3676
3677 // Emit private declaration, it will be initialized by the value we
3678 // declaration we just added to the local declarations map.
3679 EmitDecl(*PvtVD);
3680
3681 // The initialization variables reached its purpose in the emission
3682 // ofthe previous declaration, so we don't need it anymore.
3683 LocalDeclMap.erase(InitVD);
3684
3685 // Return the address of the private variable.
3686 return GetAddrOfLocalVar(PvtVD);
3687 });
3688 assert(IsRegistered && "firstprivate var already registered as private");
3689 // Silence the warning about unused variable.
3690 (void)IsRegistered;
3691
3692 ++OrigVarIt;
3693 ++InitIt;
3694 }
3695}
3696
Michael Wong65f367f2015-07-21 13:44:28 +00003697// Generate the instructions for '#pragma omp target data' directive.
3698void CodeGenFunction::EmitOMPTargetDataDirective(
3699 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003700 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3701
3702 // Create a pre/post action to signal the privatization of the device pointer.
3703 // This action can be replaced by the OpenMP runtime code generation to
3704 // deactivate privatization.
3705 bool PrivatizeDevicePointers = false;
3706 class DevicePointerPrivActionTy : public PrePostActionTy {
3707 bool &PrivatizeDevicePointers;
3708
3709 public:
3710 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3711 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3712 void Enter(CodeGenFunction &CGF) override {
3713 PrivatizeDevicePointers = true;
3714 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003715 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003716 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3717
3718 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3719 CodeGenFunction &CGF, PrePostActionTy &Action) {
3720 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3721 CGF.EmitStmt(
3722 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3723 };
3724
3725 // Codegen that selects wheather to generate the privatization code or not.
3726 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3727 &InnermostCodeGen](CodeGenFunction &CGF,
3728 PrePostActionTy &Action) {
3729 RegionCodeGenTy RCG(InnermostCodeGen);
3730 PrivatizeDevicePointers = false;
3731
3732 // Call the pre-action to change the status of PrivatizeDevicePointers if
3733 // needed.
3734 Action.Enter(CGF);
3735
3736 if (PrivatizeDevicePointers) {
3737 OMPPrivateScope PrivateScope(CGF);
3738 // Emit all instances of the use_device_ptr clause.
3739 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3740 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3741 Info.CaptureDeviceAddrMap);
3742 (void)PrivateScope.Privatize();
3743 RCG(CGF);
3744 } else
3745 RCG(CGF);
3746 };
3747
3748 // Forward the provided action to the privatization codegen.
3749 RegionCodeGenTy PrivRCG(PrivCodeGen);
3750 PrivRCG.setAction(Action);
3751
3752 // Notwithstanding the body of the region is emitted as inlined directive,
3753 // we don't use an inline scope as changes in the references inside the
3754 // region are expected to be visible outside, so we do not privative them.
3755 OMPLexicalScope Scope(CGF, S);
3756 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3757 PrivRCG);
3758 };
3759
3760 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003761
3762 // If we don't have target devices, don't bother emitting the data mapping
3763 // code.
3764 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003765 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003766 return;
3767 }
3768
3769 // Check if we have any if clause associated with the directive.
3770 const Expr *IfCond = nullptr;
3771 if (auto *C = S.getSingleClause<OMPIfClause>())
3772 IfCond = C->getCondition();
3773
3774 // Check if we have any device clause associated with the directive.
3775 const Expr *Device = nullptr;
3776 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3777 Device = C->getDevice();
3778
Samuel Antaocc10b852016-07-28 14:23:26 +00003779 // Set the action to signal privatization of device pointers.
3780 RCG.setAction(PrivAction);
3781
3782 // Emit region code.
3783 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3784 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003785}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003786
Samuel Antaodf67fc42016-01-19 19:15:56 +00003787void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3788 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003789 // If we don't have target devices, don't bother emitting the data mapping
3790 // code.
3791 if (CGM.getLangOpts().OMPTargetTriples.empty())
3792 return;
3793
3794 // Check if we have any if clause associated with the directive.
3795 const Expr *IfCond = nullptr;
3796 if (auto *C = S.getSingleClause<OMPIfClause>())
3797 IfCond = C->getCondition();
3798
3799 // Check if we have any device clause associated with the directive.
3800 const Expr *Device = nullptr;
3801 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3802 Device = C->getDevice();
3803
Samuel Antao8d2d7302016-05-26 18:30:22 +00003804 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003805}
3806
Samuel Antao72590762016-01-19 20:04:50 +00003807void CodeGenFunction::EmitOMPTargetExitDataDirective(
3808 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003809 // If we don't have target devices, don't bother emitting the data mapping
3810 // code.
3811 if (CGM.getLangOpts().OMPTargetTriples.empty())
3812 return;
3813
3814 // Check if we have any if clause associated with the directive.
3815 const Expr *IfCond = nullptr;
3816 if (auto *C = S.getSingleClause<OMPIfClause>())
3817 IfCond = C->getCondition();
3818
3819 // Check if we have any device clause associated with the directive.
3820 const Expr *Device = nullptr;
3821 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3822 Device = C->getDevice();
3823
Samuel Antao8d2d7302016-05-26 18:30:22 +00003824 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003825}
3826
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003827static void emitTargetParallelRegion(CodeGenFunction &CGF,
3828 const OMPTargetParallelDirective &S,
3829 PrePostActionTy &Action) {
3830 // Get the captured statement associated with the 'parallel' region.
3831 auto *CS = S.getCapturedStmt(OMPD_parallel);
3832 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003833 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
3834 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3835 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3836 CGF.EmitOMPPrivateClause(S, PrivateScope);
3837 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3838 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003839 // TODO: Add support for clauses.
3840 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003841 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003842 };
3843 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003844 emitPostUpdateForReductionClause(
3845 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003846}
3847
3848void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
3849 CodeGenModule &CGM, StringRef ParentName,
3850 const OMPTargetParallelDirective &S) {
3851 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3852 emitTargetParallelRegion(CGF, S, Action);
3853 };
3854 llvm::Function *Fn;
3855 llvm::Constant *Addr;
3856 // Emit target region as a standalone region.
3857 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3858 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3859 assert(Fn && Addr && "Target device function emission failed.");
3860}
3861
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003862void CodeGenFunction::EmitOMPTargetParallelDirective(
3863 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003864 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3865 emitTargetParallelRegion(CGF, S, Action);
3866 };
3867 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003868}
3869
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003870void CodeGenFunction::EmitOMPTargetParallelForDirective(
3871 const OMPTargetParallelForDirective &S) {
3872 // TODO: codegen for target parallel for.
3873}
3874
Alexey Bataev7292c292016-04-25 12:22:29 +00003875/// Emit a helper variable and return corresponding lvalue.
3876static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3877 const ImplicitParamDecl *PVD,
3878 CodeGenFunction::OMPPrivateScope &Privates) {
3879 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3880 Privates.addPrivate(
3881 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3882}
3883
3884void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3885 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3886 // Emit outlined function for task construct.
3887 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3888 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3889 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3890 const Expr *IfCond = nullptr;
3891 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3892 if (C->getNameModifier() == OMPD_unknown ||
3893 C->getNameModifier() == OMPD_taskloop) {
3894 IfCond = C->getCondition();
3895 break;
3896 }
3897 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003898
3899 OMPTaskDataTy Data;
3900 // Check if taskloop must be emitted without taskgroup.
3901 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003902 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003903 Data.Tied = true;
3904 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003905 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3906 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003907 Data.Schedule.setInt(/*IntVal=*/false);
3908 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003909 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3910 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003911 Data.Schedule.setInt(/*IntVal=*/true);
3912 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003913 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003914
3915 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3916 // if (PreCond) {
3917 // for (IV in 0..LastIteration) BODY;
3918 // <Final counter/linear vars updates>;
3919 // }
3920 //
3921
3922 // Emit: if (PreCond) - begin.
3923 // If the condition constant folds and can be elided, avoid emitting the
3924 // whole loop.
3925 bool CondConstant;
3926 llvm::BasicBlock *ContBlock = nullptr;
3927 OMPLoopScope PreInitScope(CGF, S);
3928 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3929 if (!CondConstant)
3930 return;
3931 } else {
3932 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3933 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3934 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3935 CGF.getProfileCount(&S));
3936 CGF.EmitBlock(ThenBlock);
3937 CGF.incrementProfileCounter(&S);
3938 }
3939
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003940 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3941 CGF.EmitOMPSimdInit(S);
3942
Alexey Bataev7292c292016-04-25 12:22:29 +00003943 OMPPrivateScope LoopScope(CGF);
3944 // Emit helper vars inits.
3945 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3946 auto *I = CS->getCapturedDecl()->param_begin();
3947 auto *LBP = std::next(I, LowerBound);
3948 auto *UBP = std::next(I, UpperBound);
3949 auto *STP = std::next(I, Stride);
3950 auto *LIP = std::next(I, LastIter);
3951 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3952 LoopScope);
3953 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3954 LoopScope);
3955 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3956 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3957 LoopScope);
3958 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003959 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003960 (void)LoopScope.Privatize();
3961 // Emit the loop iteration variable.
3962 const Expr *IVExpr = S.getIterationVariable();
3963 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3964 CGF.EmitVarDecl(*IVDecl);
3965 CGF.EmitIgnoredExpr(S.getInit());
3966
3967 // Emit the iterations count variable.
3968 // If it is not a variable, Sema decided to calculate iterations count on
3969 // each iteration (e.g., it is foldable into a constant).
3970 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3971 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3972 // Emit calculation of the iterations count.
3973 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3974 }
3975
3976 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3977 S.getInc(),
3978 [&S](CodeGenFunction &CGF) {
3979 CGF.EmitOMPLoopBody(S, JumpDest());
3980 CGF.EmitStopPoint(&S);
3981 },
3982 [](CodeGenFunction &) {});
3983 // Emit: if (PreCond) - end.
3984 if (ContBlock) {
3985 CGF.EmitBranch(ContBlock);
3986 CGF.EmitBlock(ContBlock, true);
3987 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003988 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3989 if (HasLastprivateClause) {
3990 CGF.EmitOMPLastprivateClauseFinal(
3991 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3992 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3993 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3994 (*LIP)->getType(), S.getLocStart())));
3995 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003996 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003997 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3998 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3999 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004000 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4001 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004002 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4003 OutlinedFn, SharedsTy,
4004 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004005 };
4006 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4007 CodeGen);
4008 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004009 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004010}
4011
Alexey Bataev49f6e782015-12-01 04:18:41 +00004012void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004013 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004014}
4015
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004016void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4017 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004018 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004019}
Samuel Antao686c70c2016-05-26 17:30:50 +00004020
4021// Generate the instructions for '#pragma omp target update' directive.
4022void CodeGenFunction::EmitOMPTargetUpdateDirective(
4023 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004024 // If we don't have target devices, don't bother emitting the data mapping
4025 // code.
4026 if (CGM.getLangOpts().OMPTargetTriples.empty())
4027 return;
4028
4029 // Check if we have any if clause associated with the directive.
4030 const Expr *IfCond = nullptr;
4031 if (auto *C = S.getSingleClause<OMPIfClause>())
4032 IfCond = C->getCondition();
4033
4034 // Check if we have any device clause associated with the directive.
4035 const Expr *Device = nullptr;
4036 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4037 Device = C->getDevice();
4038
4039 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004040}