blob: ba531b96ccf9d8febe32d0e8dba24542f9cd4bef [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.
Alexey Bataev4ba78a42016-04-27 07:56:03 +000029class OMPLexicalScope final : 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,
57 bool AsInlined = false)
58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +000060 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000061 if (AsInlined) {
62 if (S.hasAssociatedStmt()) {
63 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
64 for (auto &C : CS->captures()) {
65 if (C.capturesVariable() || C.capturesVariableByCopy()) {
66 auto *VD = C.getCapturedVar();
67 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
68 isCapturedVar(CGF, VD) ||
69 (CGF.CapturedStmtInfo &&
70 InlinedShareds.isGlobalVarCaptured(VD)),
71 VD->getType().getNonReferenceType(), VK_LValue,
72 SourceLocation());
73 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
74 return CGF.EmitLValue(&DRE).getAddress();
75 });
76 }
77 }
78 (void)InlinedShareds.Privatize();
79 }
80 }
Alexey Bataev3392d762016-02-16 11:18:12 +000081 }
82};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000083
Alexey Bataev5a3af132016-03-29 08:58:54 +000084/// Private scope for OpenMP loop-based directives, that supports capturing
85/// of used expression from loop statement.
86class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
87 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
88 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
89 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
90 for (const auto *I : PreInits->decls())
91 CGF.EmitVarDecl(cast<VarDecl>(*I));
92 }
93 }
94 }
95
96public:
97 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
98 : CodeGenFunction::RunCleanupsScope(CGF) {
99 emitPreInitStmt(CGF, S);
100 }
101};
102
Alexey Bataev3392d762016-02-16 11:18:12 +0000103} // namespace
104
Alexey Bataev1189bd02016-01-26 12:20:39 +0000105llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
106 auto &C = getContext();
107 llvm::Value *Size = nullptr;
108 auto SizeInChars = C.getTypeSizeInChars(Ty);
109 if (SizeInChars.isZero()) {
110 // getTypeSizeInChars() returns 0 for a VLA.
111 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
112 llvm::Value *ArraySize;
113 std::tie(ArraySize, Ty) = getVLASize(VAT);
114 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
115 }
116 SizeInChars = C.getTypeSizeInChars(Ty);
117 if (SizeInChars.isZero())
118 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
119 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
120 } else
121 Size = CGM.getSize(SizeInChars);
122 return Size;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 const RecordDecl *RD = S.getCapturedRecordDecl();
128 auto CurField = RD->field_begin();
129 auto CurCap = S.captures().begin();
130 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
131 E = S.capture_init_end();
132 I != E; ++I, ++CurField, ++CurCap) {
133 if (CurField->hasCapturedVLAType()) {
134 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000135 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000136 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000137 } else if (CurCap->capturesThis())
138 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000139 else if (CurCap->capturesVariableByCopy()) {
140 llvm::Value *CV =
141 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
142
143 // If the field is not a pointer, we need to save the actual value
144 // and load it as a void pointer.
145 if (!CurField->getType()->isAnyPointerType()) {
146 auto &Ctx = getContext();
147 auto DstAddr = CreateMemTemp(
148 Ctx.getUIntPtrType(),
149 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
150 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
151
152 auto *SrcAddrVal = EmitScalarConversion(
153 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
154 Ctx.getPointerType(CurField->getType()), SourceLocation());
155 LValue SrcLV =
156 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
157
158 // Store the value using the source type pointer.
159 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
160
161 // Load the value using the destination type pointer.
162 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
163 }
164 CapturedVars.push_back(CV);
165 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000166 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000167 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000168 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000169 }
170}
171
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000172static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
173 StringRef Name, LValue AddrLV,
174 bool isReferenceType = false) {
175 ASTContext &Ctx = CGF.getContext();
176
177 auto *CastedPtr = CGF.EmitScalarConversion(
178 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
179 Ctx.getPointerType(DstType), SourceLocation());
180 auto TmpAddr =
181 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
182 .getAddress();
183
184 // If we are dealing with references we need to return the address of the
185 // reference instead of the reference of the value.
186 if (isReferenceType) {
187 QualType RefType = Ctx.getLValueReferenceType(DstType);
188 auto *RefVal = TmpAddr.getPointer();
189 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
190 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000191 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000192 }
193
194 return TmpAddr;
195}
196
Alexey Bataev2377fe92015-09-10 08:12:02 +0000197llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000198CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000199 assert(
200 CapturedStmtInfo &&
201 "CapturedStmtInfo should be set when generating the captured function");
202 const CapturedDecl *CD = S.getCapturedDecl();
203 const RecordDecl *RD = S.getCapturedRecordDecl();
204 assert(CD->hasBody() && "missing CapturedDecl body");
205
206 // Build the argument list.
207 ASTContext &Ctx = CGM.getContext();
208 FunctionArgList Args;
209 Args.append(CD->param_begin(),
210 std::next(CD->param_begin(), CD->getContextParamPosition()));
211 auto I = S.captures().begin();
212 for (auto *FD : RD->fields()) {
213 QualType ArgType = FD->getType();
214 IdentifierInfo *II = nullptr;
215 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000216
217 // If this is a capture by copy and the type is not a pointer, the outlined
218 // function argument type should be uintptr and the value properly casted to
219 // uintptr. This is necessary given that the runtime library is only able to
220 // deal with pointers. We can pass in the same way the VLA type sizes to the
221 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000222 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
223 I->capturesVariableArrayType())
224 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225
226 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000227 CapVar = I->getCapturedVar();
228 II = CapVar->getIdentifier();
229 } else if (I->capturesThis())
230 II = &getContext().Idents.get("this");
231 else {
232 assert(I->capturesVariableArrayType());
233 II = &getContext().Idents.get("vla");
234 }
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000235 if (ArgType->isVariablyModifiedType()) {
236 bool IsReference = ArgType->isLValueReferenceType();
237 ArgType =
238 getContext().getCanonicalParamType(ArgType.getNonReferenceType());
239 if (IsReference && !ArgType->isPointerType()) {
240 ArgType = getContext().getLValueReferenceType(
241 ArgType, /*SpelledAsLValue=*/false);
242 }
243 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
245 FD->getLocation(), II, ArgType));
246 ++I;
247 }
248 Args.append(
249 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
250 CD->param_end());
251
252 // Create the function declaration.
253 FunctionType::ExtInfo ExtInfo;
254 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000255 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000256 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
257
258 llvm::Function *F = llvm::Function::Create(
259 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
260 CapturedStmtInfo->getHelperName(), &CGM.getModule());
261 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
262 if (CD->isNothrow())
263 F->addFnAttr(llvm::Attribute::NoUnwind);
264
265 // Generate the function.
266 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
267 CD->getBody()->getLocStart());
268 unsigned Cnt = CD->getContextParamPosition();
269 I = S.captures().begin();
270 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000271 // If we are capturing a pointer by copy we don't need to do anything, just
272 // use the value that we get from the arguments.
273 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000274 const VarDecl *CurVD = I->getCapturedVar();
275 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
276 // If the variable is a reference we need to materialize it here.
277 if (CurVD->getType()->isReferenceType()) {
278 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
279 ".materialized_ref");
280 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
281 CurVD->getType());
282 LocalAddr = RefAddr;
283 }
284 setAddrOfLocalVar(CurVD, LocalAddr);
Richard Trieucc3949d2016-02-18 22:34:54 +0000285 ++Cnt;
286 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000287 continue;
288 }
289
Alexey Bataev2377fe92015-09-10 08:12:02 +0000290 LValue ArgLVal =
291 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
292 AlignmentSource::Decl);
293 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000295 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
296 Args[Cnt]->getName(), ArgLVal),
297 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000298 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000299 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000300 auto VAT = FD->getCapturedVLAType();
301 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
302 } else if (I->capturesVariable()) {
303 auto *Var = I->getCapturedVar();
304 QualType VarTy = Var->getType();
305 Address ArgAddr = ArgLVal.getAddress();
306 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000307 if (ArgLVal.getType()->isLValueReferenceType()) {
308 ArgAddr = EmitLoadOfReference(
309 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000310 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000311 assert(ArgLVal.getType()->isPointerType());
312 ArgAddr = EmitLoadOfPointer(
313 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
314 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000315 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000316 setAddrOfLocalVar(
317 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000318 } else if (I->capturesVariableByCopy()) {
319 assert(!FD->getType()->isAnyPointerType() &&
320 "Not expecting a captured pointer.");
321 auto *Var = I->getCapturedVar();
322 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000323 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
324 Args[Cnt]->getName(), ArgLVal,
325 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000326 } else {
327 // If 'this' is captured, load it into CXXThisValue.
328 assert(I->capturesThis());
329 CXXThisValue =
330 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
331 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000332 ++Cnt;
333 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000334 }
335
Serge Pavlov3a561452015-12-06 14:32:39 +0000336 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000337 CapturedStmtInfo->EmitBody(*this, CD->getBody());
338 FinishFunction(CD->getBodyRBrace());
339
340 return F;
341}
342
Alexey Bataev9959db52014-05-06 10:08:46 +0000343//===----------------------------------------------------------------------===//
344// OpenMP Directive Emission
345//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000346void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000347 Address DestAddr, Address SrcAddr, QualType OriginalType,
348 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000349 // Perform element-by-element initialization.
350 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000351
352 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000353 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000354 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
355 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
356
357 auto SrcBegin = SrcAddr.getPointer();
358 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000359 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000360 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
361 // The basic structure here is a while-do loop.
362 auto BodyBB = createBasicBlock("omp.arraycpy.body");
363 auto DoneBB = createBasicBlock("omp.arraycpy.done");
364 auto IsEmpty =
365 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
366 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000367
Alexey Bataev420d45b2015-04-14 05:11:24 +0000368 // Enter the loop body, making that address the current address.
369 auto EntryBB = Builder.GetInsertBlock();
370 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000371
372 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
373
374 llvm::PHINode *SrcElementPHI =
375 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
376 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
377 Address SrcElementCurrent =
378 Address(SrcElementPHI,
379 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
380
381 llvm::PHINode *DestElementPHI =
382 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
383 DestElementPHI->addIncoming(DestBegin, EntryBB);
384 Address DestElementCurrent =
385 Address(DestElementPHI,
386 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000387
Alexey Bataev420d45b2015-04-14 05:11:24 +0000388 // Emit copy.
389 CopyGen(DestElementCurrent, SrcElementCurrent);
390
391 // Shift the address forward by one element.
392 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000393 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000394 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000395 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000396 // Check whether we've reached the end.
397 auto Done =
398 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
399 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000400 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
401 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000402
403 // Done.
404 EmitBlock(DoneBB, /*IsFinished=*/true);
405}
406
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000407/// Check if the combiner is a call to UDR combiner and if it is so return the
408/// UDR decl used for reduction.
409static const OMPDeclareReductionDecl *
410getReductionInit(const Expr *ReductionOp) {
411 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
412 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
413 if (auto *DRE =
414 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
415 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
416 return DRD;
417 return nullptr;
418}
419
420static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
421 const OMPDeclareReductionDecl *DRD,
422 const Expr *InitOp,
423 Address Private, Address Original,
424 QualType Ty) {
425 if (DRD->getInitializer()) {
426 std::pair<llvm::Function *, llvm::Function *> Reduction =
427 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
428 auto *CE = cast<CallExpr>(InitOp);
429 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
430 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
431 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
432 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
433 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
434 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
435 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
436 [=]() -> Address { return Private; });
437 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
438 [=]() -> Address { return Original; });
439 (void)PrivateScope.Privatize();
440 RValue Func = RValue::get(Reduction.second);
441 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
442 CGF.EmitIgnoredExpr(InitOp);
443 } else {
444 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
445 auto *GV = new llvm::GlobalVariable(
446 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
447 llvm::GlobalValue::PrivateLinkage, Init, ".init");
448 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
449 RValue InitRVal;
450 switch (CGF.getEvaluationKind(Ty)) {
451 case TEK_Scalar:
452 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
453 break;
454 case TEK_Complex:
455 InitRVal =
456 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
457 break;
458 case TEK_Aggregate:
459 InitRVal = RValue::getAggregate(LV.getAddress());
460 break;
461 }
462 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
463 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
464 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
465 /*IsInitializer=*/false);
466 }
467}
468
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000469/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000470/// \param DestAddr Address of the array.
471/// \param Type Type of array.
472/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000473/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000474static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000475 QualType Type, const Expr *Init,
476 Address SrcAddr = Address::invalid()) {
477 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000478 // Perform element-by-element initialization.
479 QualType ElementTy;
480
481 // Drill down to the base element type on both arrays.
482 auto ArrayTy = Type->getAsArrayTypeUnsafe();
483 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
484 DestAddr =
485 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000486 if (DRD)
487 SrcAddr =
488 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000489
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000490 llvm::Value *SrcBegin = nullptr;
491 if (DRD)
492 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000493 auto DestBegin = DestAddr.getPointer();
494 // Cast from pointer to array type to pointer to single element.
495 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
496 // The basic structure here is a while-do loop.
497 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
498 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
499 auto IsEmpty =
500 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
501 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
502
503 // Enter the loop body, making that address the current address.
504 auto EntryBB = CGF.Builder.GetInsertBlock();
505 CGF.EmitBlock(BodyBB);
506
507 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
508
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000509 llvm::PHINode *SrcElementPHI = nullptr;
510 Address SrcElementCurrent = Address::invalid();
511 if (DRD) {
512 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
513 "omp.arraycpy.srcElementPast");
514 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
515 SrcElementCurrent =
516 Address(SrcElementPHI,
517 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
518 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000519 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
520 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
521 DestElementPHI->addIncoming(DestBegin, EntryBB);
522 Address DestElementCurrent =
523 Address(DestElementPHI,
524 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
525
526 // Emit copy.
527 {
528 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000529 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000530 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
531 SrcElementCurrent, ElementTy);
532 } else
533 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
534 /*IsInitializer=*/false);
535 }
536
537 if (DRD) {
538 // Shift the address forward by one element.
539 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
540 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
541 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000542 }
543
544 // Shift the address forward by one element.
545 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
546 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
547 // Check whether we've reached the end.
548 auto Done =
549 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
550 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
551 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
552
553 // Done.
554 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
555}
556
John McCall7f416cc2015-09-08 08:05:57 +0000557void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
558 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000559 const VarDecl *SrcVD, const Expr *Copy) {
560 if (OriginalType->isArrayType()) {
561 auto *BO = dyn_cast<BinaryOperator>(Copy);
562 if (BO && BO->getOpcode() == BO_Assign) {
563 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000564 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000565 } else {
566 // For arrays with complex element types perform element by element
567 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000568 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000569 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000570 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000571 // Working with the single array element, so have to remap
572 // destination and source variables to corresponding array
573 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000574 CodeGenFunction::OMPPrivateScope Remap(*this);
575 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000576 return DestElement;
577 });
578 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000579 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000580 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000581 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000582 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000583 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000584 } else {
585 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000586 CodeGenFunction::OMPPrivateScope Remap(*this);
587 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
588 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000589 (void)Remap.Privatize();
590 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000591 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000592 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000593}
594
Alexey Bataev69c62a92015-04-15 04:52:20 +0000595bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
596 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000597 if (!HaveInsertPoint())
598 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000599 bool FirstprivateIsLastprivate = false;
600 llvm::DenseSet<const VarDecl *> Lastprivates;
601 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
602 for (const auto *D : C->varlists())
603 Lastprivates.insert(
604 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
605 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000606 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000607 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000608 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000609 auto IRef = C->varlist_begin();
610 auto InitsRef = C->inits().begin();
611 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000612 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000613 bool ThisFirstprivateIsLastprivate =
614 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000615 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000616 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000617 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000618 !FD->getType()->isReferenceType()) {
619 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
620 ++IRef;
621 ++InitsRef;
622 continue;
623 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000624 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000625 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000626 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
628 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
629 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000630 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
631 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
632 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000634 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000635 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000636 // Emit VarDecl with copy init for arrays.
637 // Get the address of the original variable captured in current
638 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000639 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000640 auto Emission = EmitAutoVarAlloca(*VD);
641 auto *Init = VD->getInit();
642 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
643 // Perform simple memcpy.
644 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000645 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000646 } else {
647 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000648 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000649 [this, VDInit, Init](Address DestElement,
650 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000651 // Clean up any temporaries needed by the initialization.
652 RunCleanupsScope InitScope(*this);
653 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000654 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000655 EmitAnyExprToMem(Init, DestElement,
656 Init->getType().getQualifiers(),
657 /*IsInitializer*/ false);
658 LocalDeclMap.erase(VDInit);
659 });
660 }
661 EmitAutoVarCleanups(Emission);
662 return Emission.getAllocatedAddress();
663 });
664 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000665 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000666 // Emit private VarDecl with copy init.
667 // Remap temp VDInit variable to the address of the original
668 // variable
669 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000670 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000671 EmitDecl(*VD);
672 LocalDeclMap.erase(VDInit);
673 return GetAddrOfLocalVar(VD);
674 });
675 }
676 assert(IsRegistered &&
677 "firstprivate var already registered as private");
678 // Silence the warning about unused variable.
679 (void)IsRegistered;
680 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000681 ++IRef;
682 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000683 }
684 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000685 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000686}
687
Alexey Bataev03b340a2014-10-21 03:16:40 +0000688void CodeGenFunction::EmitOMPPrivateClause(
689 const OMPExecutableDirective &D,
690 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000691 if (!HaveInsertPoint())
692 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000693 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000694 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000695 auto IRef = C->varlist_begin();
696 for (auto IInit : C->private_copies()) {
697 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000698 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
699 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
700 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000701 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000702 // Emit private VarDecl with copy init.
703 EmitDecl(*VD);
704 return GetAddrOfLocalVar(VD);
705 });
706 assert(IsRegistered && "private var already registered as private");
707 // Silence the warning about unused variable.
708 (void)IsRegistered;
709 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000710 ++IRef;
711 }
712 }
713}
714
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000715bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000716 if (!HaveInsertPoint())
717 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000718 // threadprivate_var1 = master_threadprivate_var1;
719 // operator=(threadprivate_var2, master_threadprivate_var2);
720 // ...
721 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000722 llvm::DenseSet<const VarDecl *> CopiedVars;
723 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000724 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000725 auto IRef = C->varlist_begin();
726 auto ISrcRef = C->source_exprs().begin();
727 auto IDestRef = C->destination_exprs().begin();
728 for (auto *AssignOp : C->assignment_ops()) {
729 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000730 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000731 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000732 // Get the address of the master variable. If we are emitting code with
733 // TLS support, the address is passed from the master as field in the
734 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000735 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000736 if (getLangOpts().OpenMPUseTLS &&
737 getContext().getTargetInfo().isTLSSupported()) {
738 assert(CapturedStmtInfo->lookup(VD) &&
739 "Copyin threadprivates should have been captured!");
740 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
741 VK_LValue, (*IRef)->getExprLoc());
742 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000743 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000744 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000745 MasterAddr =
746 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
747 : CGM.GetAddrOfGlobal(VD),
748 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000749 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000750 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000752 if (CopiedVars.size() == 1) {
753 // At first check if current thread is a master thread. If it is, no
754 // need to copy data.
755 CopyBegin = createBasicBlock("copyin.not.master");
756 CopyEnd = createBasicBlock("copyin.not.master.end");
757 Builder.CreateCondBr(
758 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000759 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
760 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000761 CopyBegin, CopyEnd);
762 EmitBlock(CopyBegin);
763 }
764 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
765 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000766 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000767 }
768 ++IRef;
769 ++ISrcRef;
770 ++IDestRef;
771 }
772 }
773 if (CopyEnd) {
774 // Exit out of copying procedure for non-master thread.
775 EmitBlock(CopyEnd, /*IsFinished=*/true);
776 return true;
777 }
778 return false;
779}
780
Alexey Bataev38e89532015-04-16 04:54:05 +0000781bool CodeGenFunction::EmitOMPLastprivateClauseInit(
782 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000783 if (!HaveInsertPoint())
784 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000785 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000786 llvm::DenseSet<const VarDecl *> SIMDLCVs;
787 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
788 auto *LoopDirective = cast<OMPLoopDirective>(&D);
789 for (auto *C : LoopDirective->counters()) {
790 SIMDLCVs.insert(
791 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
792 }
793 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000794 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000795 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000796 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000797 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
798 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000799 auto IRef = C->varlist_begin();
800 auto IDestRef = C->destination_exprs().begin();
801 for (auto *IInit : C->private_copies()) {
802 // Keep the address of the original variable for future update at the end
803 // of the loop.
804 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000805 // Taskloops do not require additional initialization, it is done in
806 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000807 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
808 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000809 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000810 DeclRefExpr DRE(
811 const_cast<VarDecl *>(OrigVD),
812 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
813 OrigVD) != nullptr,
814 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
815 return EmitLValue(&DRE).getAddress();
816 });
817 // Check if the variable is also a firstprivate: in this case IInit is
818 // not generated. Initialization of this variable will happen in codegen
819 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000820 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000821 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000822 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
823 // Emit private VarDecl with copy init.
824 EmitDecl(*VD);
825 return GetAddrOfLocalVar(VD);
826 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000827 assert(IsRegistered &&
828 "lastprivate var already registered as private");
829 (void)IsRegistered;
830 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000831 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000832 ++IRef;
833 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000834 }
835 }
836 return HasAtLeastOneLastprivate;
837}
838
839void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000840 const OMPExecutableDirective &D, bool NoFinals,
841 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000842 if (!HaveInsertPoint())
843 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000844 // Emit following code:
845 // if (<IsLastIterCond>) {
846 // orig_var1 = private_orig_var1;
847 // ...
848 // orig_varn = private_orig_varn;
849 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000850 llvm::BasicBlock *ThenBB = nullptr;
851 llvm::BasicBlock *DoneBB = nullptr;
852 if (IsLastIterCond) {
853 ThenBB = createBasicBlock(".omp.lastprivate.then");
854 DoneBB = createBasicBlock(".omp.lastprivate.done");
855 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
856 EmitBlock(ThenBB);
857 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000858 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
859 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000860 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000861 auto IC = LoopDirective->counters().begin();
862 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000863 auto *D =
864 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
865 if (NoFinals)
866 AlreadyEmittedVars.insert(D);
867 else
868 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000869 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000870 }
871 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000872 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
873 auto IRef = C->varlist_begin();
874 auto ISrcRef = C->source_exprs().begin();
875 auto IDestRef = C->destination_exprs().begin();
876 for (auto *AssignOp : C->assignment_ops()) {
877 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
878 QualType Type = PrivateVD->getType();
879 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
880 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
881 // If lastprivate variable is a loop control variable for loop-based
882 // directive, update its value before copyin back to original
883 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000884 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
885 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000886 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
887 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
888 // Get the address of the original variable.
889 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
890 // Get the address of the private variable.
891 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
892 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
893 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000894 Address(Builder.CreateLoad(PrivateAddr),
895 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000896 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000897 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000898 ++IRef;
899 ++ISrcRef;
900 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000901 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000902 if (auto *PostUpdate = C->getPostUpdateExpr())
903 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000904 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000905 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000906 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000907}
908
Alexey Bataev31300ed2016-02-04 11:27:03 +0000909static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
910 LValue BaseLV, llvm::Value *Addr) {
911 Address Tmp = Address::invalid();
912 Address TopTmp = Address::invalid();
913 Address MostTopTmp = Address::invalid();
914 BaseTy = BaseTy.getNonReferenceType();
915 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
916 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
917 Tmp = CGF.CreateMemTemp(BaseTy);
918 if (TopTmp.isValid())
919 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
920 else
921 MostTopTmp = Tmp;
922 TopTmp = Tmp;
923 BaseTy = BaseTy->getPointeeType();
924 }
925 llvm::Type *Ty = BaseLV.getPointer()->getType();
926 if (Tmp.isValid())
927 Ty = Tmp.getElementType();
928 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
929 if (Tmp.isValid()) {
930 CGF.Builder.CreateStore(Addr, Tmp);
931 return MostTopTmp;
932 }
933 return Address(Addr, BaseLV.getAlignment());
934}
935
936static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
937 LValue BaseLV) {
938 BaseTy = BaseTy.getNonReferenceType();
939 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
940 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
941 if (auto *PtrTy = BaseTy->getAs<PointerType>())
942 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
943 else {
944 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
945 BaseTy->castAs<ReferenceType>());
946 }
947 BaseTy = BaseTy->getPointeeType();
948 }
949 return CGF.MakeAddrLValue(
950 Address(
951 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
952 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
953 BaseLV.getAlignment()),
954 BaseLV.getType(), BaseLV.getAlignmentSource());
955}
956
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000957void CodeGenFunction::EmitOMPReductionClauseInit(
958 const OMPExecutableDirective &D,
959 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000960 if (!HaveInsertPoint())
961 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000963 auto ILHS = C->lhs_exprs().begin();
964 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000965 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000966 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000967 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000968 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000969 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
970 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000971 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000972 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
973 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
974 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
975 Base = TempOASE->getBase()->IgnoreParenImpCasts();
976 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
977 Base = TempASE->getBase()->IgnoreParenImpCasts();
978 auto *DE = cast<DeclRefExpr>(Base);
979 auto *OrigVD = cast<VarDecl>(DE->getDecl());
980 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
981 auto OASELValueUB =
982 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
983 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000984 LValue BaseLValue =
985 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
986 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000987 // Store the address of the original variable associated with the LHS
988 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +0000989 PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000990 return OASELValueLB.getAddress();
991 });
992 // Emit reduction copy.
993 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000994 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000995 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000996 // Emit VarDecl with copy init for arrays.
997 // Get the address of the original variable captured in current
998 // captured region.
999 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
1000 OASELValueLB.getPointer());
1001 Size = Builder.CreateNUWAdd(
1002 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
1003 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1004 *this, cast<OpaqueValueExpr>(
1005 getContext()
1006 .getAsVariableArrayType(PrivateVD->getType())
1007 ->getSizeExpr()),
1008 RValue::get(Size));
1009 EmitVariablyModifiedType(PrivateVD->getType());
1010 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1011 auto Addr = Emission.getAllocatedAddress();
1012 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001013 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1014 DRD ? *IRed : Init,
1015 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001016 EmitAutoVarCleanups(Emission);
1017 // Emit private VarDecl with reduction init.
1018 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1019 OASELValueLB.getPointer());
1020 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001021 return castToBase(*this, OrigVD->getType(),
1022 OASELValueLB.getType(), OriginalBaseLValue,
1023 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001024 });
1025 assert(IsRegistered && "private var already registered as private");
1026 // Silence the warning about unused variable.
1027 (void)IsRegistered;
1028 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1029 return GetAddrOfLocalVar(PrivateVD);
1030 });
1031 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1032 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1033 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1034 Base = TempASE->getBase()->IgnoreParenImpCasts();
1035 auto *DE = cast<DeclRefExpr>(Base);
1036 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1037 auto ASELValue = EmitLValue(ASE);
1038 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001039 LValue BaseLValue = loadToBegin(
1040 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001041 // Store the address of the original variable associated with the LHS
1042 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001043 PrivateScope.addPrivate(
1044 LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001045 // Emit reduction copy.
1046 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001047 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001048 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001049 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001050 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1051 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001052 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001053 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1054 ASELValue.getAddress(),
1055 ASELValue.getType());
1056 } else
1057 EmitAutoVarInit(Emission);
1058 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001059 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1060 ASELValue.getPointer());
1061 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001062 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1063 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001064 });
1065 assert(IsRegistered && "private var already registered as private");
1066 // Silence the warning about unused variable.
1067 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001068 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1069 return Builder.CreateElementBitCast(
1070 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1071 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001072 });
1073 } else {
1074 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001075 QualType Type = PrivateVD->getType();
1076 if (getContext().getAsArrayType(Type)) {
1077 // Store the address of the original variable associated with the LHS
1078 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001079 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1080 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1081 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001082 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001083 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001084 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001085 OriginalAddr = Builder.CreateElementBitCast(
1086 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1087 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001088 });
1089 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1090 if (Type->isVariablyModifiedType()) {
1091 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1092 *this, cast<OpaqueValueExpr>(
1093 getContext()
1094 .getAsVariableArrayType(PrivateVD->getType())
1095 ->getSizeExpr()),
1096 RValue::get(
1097 getTypeSize(OrigVD->getType().getNonReferenceType())));
1098 EmitVariablyModifiedType(Type);
1099 }
1100 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1101 auto Addr = Emission.getAllocatedAddress();
1102 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001103 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1104 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001105 EmitAutoVarCleanups(Emission);
1106 return Emission.getAllocatedAddress();
1107 });
1108 assert(IsRegistered && "private var already registered as private");
1109 // Silence the warning about unused variable.
1110 (void)IsRegistered;
1111 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1112 return Builder.CreateElementBitCast(
1113 GetAddrOfLocalVar(PrivateVD),
1114 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1115 });
1116 } else {
1117 // Store the address of the original variable associated with the LHS
1118 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001119 Address OriginalAddr = Address::invalid();
1120 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1121 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001122 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1123 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1124 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001125 OriginalAddr = EmitLValue(&DRE).getAddress();
1126 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001127 });
1128 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001129 bool IsRegistered = PrivateScope.addPrivate(
1130 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001131 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001132 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1133 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001134 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001135 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1136 OriginalAddr,
1137 PrivateVD->getType());
1138 } else
1139 EmitAutoVarInit(Emission);
1140 EmitAutoVarCleanups(Emission);
1141 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001142 });
1143 assert(IsRegistered && "private var already registered as private");
1144 // Silence the warning about unused variable.
1145 (void)IsRegistered;
1146 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1147 return GetAddrOfLocalVar(PrivateVD);
1148 });
1149 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001150 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001151 ++ILHS;
1152 ++IRHS;
1153 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001154 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001155 }
1156 }
1157}
1158
1159void CodeGenFunction::EmitOMPReductionClauseFinal(
1160 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001161 if (!HaveInsertPoint())
1162 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001163 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 llvm::SmallVector<const Expr *, 8> LHSExprs;
1165 llvm::SmallVector<const Expr *, 8> RHSExprs;
1166 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001167 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001168 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001169 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001170 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001171 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1172 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1173 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1174 }
1175 if (HasAtLeastOneReduction) {
1176 // Emit nowait reduction if nowait clause is present or directive is a
1177 // parallel directive (it always has implicit barrier).
1178 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001179 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001180 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001181 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1182 D.getDirectiveKind() == OMPD_simd,
1183 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001184 }
1185}
1186
Alexey Bataev61205072016-03-02 04:57:40 +00001187static void emitPostUpdateForReductionClause(
1188 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1189 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1190 if (!CGF.HaveInsertPoint())
1191 return;
1192 llvm::BasicBlock *DoneBB = nullptr;
1193 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1194 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1195 if (!DoneBB) {
1196 if (auto *Cond = CondGen(CGF)) {
1197 // If the first post-update expression is found, emit conditional
1198 // block if it was requested.
1199 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1200 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1201 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1202 CGF.EmitBlock(ThenBB);
1203 }
1204 }
1205 CGF.EmitIgnoredExpr(PostUpdate);
1206 }
1207 }
1208 if (DoneBB)
1209 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1210}
1211
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1213 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001214 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001216 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1217 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1218 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001219 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001220 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001221 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1222 /*IgnoreResultAssign*/ true);
1223 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1224 CGF, NumThreads, NumThreadsClause->getLocStart());
1225 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001226 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001227 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001228 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1229 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1230 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001231 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001232 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1233 if (C->getNameModifier() == OMPD_unknown ||
1234 C->getNameModifier() == OMPD_parallel) {
1235 IfCond = C->getCondition();
1236 break;
1237 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001238 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001239
1240 OMPLexicalScope Scope(CGF, S);
1241 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1242 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001243 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001244 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245}
1246
1247void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001248 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001249 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001250 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001251 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001252 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1253 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001254 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001255 // propagation master's thread values of threadprivate variables to local
1256 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001257 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1258 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1259 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001260 }
1261 CGF.EmitOMPPrivateClause(S, PrivateScope);
1262 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1263 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001265 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001267 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001268 emitPostUpdateForReductionClause(
1269 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001270}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001271
Alexey Bataev0f34da12015-07-02 04:17:07 +00001272void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1273 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001274 RunCleanupsScope BodyScope(*this);
1275 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001276 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001277 EmitIgnoredExpr(I);
1278 }
Alexander Musman3276a272015-03-21 10:12:56 +00001279 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001280 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001281 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001282 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001283 }
1284
Alexander Musmana5f070a2014-10-01 06:03:56 +00001285 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001286 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001287 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001288 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001289 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001290 // The end (updates/cleanups).
1291 EmitBlock(Continue.getBlock());
1292 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001293}
1294
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001295void CodeGenFunction::EmitOMPInnerLoop(
1296 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1297 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001298 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1299 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001300 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001301
1302 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001303 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001304 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001305 const SourceRange &R = S.getSourceRange();
1306 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1307 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001308
1309 // If there are any cleanups between here and the loop-exit scope,
1310 // create a block to stage a loop exit along.
1311 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001312 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001313 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314
Alexander Musmand196ef22014-10-07 08:57:09 +00001315 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001316
Alexey Bataev2df54a02015-03-12 08:53:29 +00001317 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001318 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001319 if (ExitBlock != LoopExit.getBlock()) {
1320 EmitBlock(ExitBlock);
1321 EmitBranchThroughCleanup(LoopExit);
1322 }
1323
1324 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001325 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326
1327 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001328 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001329 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1330
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001331 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001332
1333 // Emit "IV = IV + 1" and a back-edge to the condition block.
1334 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001335 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001336 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001337 BreakContinueStack.pop_back();
1338 EmitBranch(CondBlock);
1339 LoopStack.pop();
1340 // Emit the fall-through block.
1341 EmitBlock(LoopExit.getBlock());
1342}
1343
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001344void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001345 if (!HaveInsertPoint())
1346 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001347 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001348 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001349 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001350 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001351 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1352 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1353 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1354 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1355 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1356 VD->getInit()->getType(), VK_LValue,
1357 VD->getInit()->getExprLoc());
1358 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1359 VD->getType()),
1360 /*capturedByInit=*/false);
1361 EmitAutoVarCleanups(Emission);
1362 } else
1363 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001364 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001365 // Emit the linear steps for the linear clauses.
1366 // If a step is not constant, it is pre-calculated before the loop.
1367 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1368 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001369 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001370 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001371 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001372 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001373 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001374}
1375
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001376void CodeGenFunction::EmitOMPLinearClauseFinal(
1377 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001378 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001379 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001380 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001381 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001382 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001383 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001384 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001385 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001386 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001387 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001388 // If the first post-update expression is found, emit conditional
1389 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001390 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1391 DoneBB = createBasicBlock(".omp.linear.pu.done");
1392 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1393 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001394 }
1395 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001396 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1397 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001399 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400 Address OrigAddr = EmitLValue(&DRE).getAddress();
1401 CodeGenFunction::OMPPrivateScope VarScope(*this);
1402 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001403 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001404 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001405 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001406 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001407 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001408 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001409 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001410 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001412}
1413
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001414static void emitAlignedClause(CodeGenFunction &CGF,
1415 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001416 if (!CGF.HaveInsertPoint())
1417 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001418 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001419 unsigned ClauseAlignment = 0;
1420 if (auto AlignmentExpr = Clause->getAlignment()) {
1421 auto AlignmentCI =
1422 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1423 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001424 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001425 for (auto E : Clause->varlists()) {
1426 unsigned Alignment = ClauseAlignment;
1427 if (Alignment == 0) {
1428 // OpenMP [2.8.1, Description]
1429 // If no optional parameter is specified, implementation-defined default
1430 // alignments for SIMD instructions on the target platforms are assumed.
1431 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001432 CGF.getContext()
1433 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1434 E->getType()->getPointeeType()))
1435 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001436 }
1437 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1438 "alignment is not power of 2");
1439 if (Alignment != 0) {
1440 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1441 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1442 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001443 }
1444 }
1445}
1446
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001447void CodeGenFunction::EmitOMPPrivateLoopCounters(
1448 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1449 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001450 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001451 auto I = S.private_counters().begin();
1452 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001453 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1454 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001455 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001456 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001457 if (!LocalDeclMap.count(PrivateVD)) {
1458 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1459 EmitAutoVarCleanups(VarEmission);
1460 }
1461 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1462 /*RefersToEnclosingVariableOrCapture=*/false,
1463 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1464 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001465 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001466 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1467 VD->hasGlobalStorage()) {
1468 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1469 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1470 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1471 E->getType(), VK_LValue, E->getExprLoc());
1472 return EmitLValue(&DRE).getAddress();
1473 });
1474 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001475 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001476 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001477}
1478
Alexey Bataev62dbb972015-04-22 11:59:37 +00001479static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1480 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1481 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001482 if (!CGF.HaveInsertPoint())
1483 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001484 {
1485 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001486 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001487 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001488 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001489 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001490 CGF.EmitIgnoredExpr(I);
1491 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001492 }
1493 // Check that loop is executed at least one time.
1494 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1495}
1496
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001497void CodeGenFunction::EmitOMPLinearClause(
1498 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1499 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001500 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001501 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1502 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1503 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1504 for (auto *C : LoopDirective->counters()) {
1505 SIMDLCVs.insert(
1506 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1507 }
1508 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001509 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001510 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001511 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001512 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1513 auto *PrivateVD =
1514 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001515 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1516 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1517 // Emit private VarDecl with copy init.
1518 EmitVarDecl(*PrivateVD);
1519 return GetAddrOfLocalVar(PrivateVD);
1520 });
1521 assert(IsRegistered && "linear var already registered as private");
1522 // Silence the warning about unused variable.
1523 (void)IsRegistered;
1524 } else
1525 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001526 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001527 }
1528 }
1529}
1530
Alexey Bataev45bfad52015-08-21 12:19:04 +00001531static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001532 const OMPExecutableDirective &D,
1533 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001534 if (!CGF.HaveInsertPoint())
1535 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001536 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001537 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1538 /*ignoreResult=*/true);
1539 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1540 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1541 // In presence of finite 'safelen', it may be unsafe to mark all
1542 // the memory instructions parallel, because loop-carried
1543 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001544 if (!IsMonotonic)
1545 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001546 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001547 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1548 /*ignoreResult=*/true);
1549 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001550 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001551 // In presence of finite 'safelen', it may be unsafe to mark all
1552 // the memory instructions parallel, because loop-carried
1553 // dependences of 'safelen' iterations are possible.
1554 CGF.LoopStack.setParallel(false);
1555 }
1556}
1557
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001558void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1559 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001560 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001561 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001562 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001563 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001564}
1565
Alexey Bataevef549a82016-03-09 09:49:09 +00001566void CodeGenFunction::EmitOMPSimdFinal(
1567 const OMPLoopDirective &D,
1568 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001569 if (!HaveInsertPoint())
1570 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001571 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001572 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001573 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001574 for (auto F : D.finals()) {
1575 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001576 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1577 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1578 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1579 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001580 if (!DoneBB) {
1581 if (auto *Cond = CondGen(*this)) {
1582 // If the first post-update expression is found, emit conditional
1583 // block if it was requested.
1584 auto *ThenBB = createBasicBlock(".omp.final.then");
1585 DoneBB = createBasicBlock(".omp.final.done");
1586 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1587 EmitBlock(ThenBB);
1588 }
1589 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001590 Address OrigAddr = Address::invalid();
1591 if (CED)
1592 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1593 else {
1594 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1595 /*RefersToEnclosingVariableOrCapture=*/false,
1596 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1597 OrigAddr = EmitLValue(&DRE).getAddress();
1598 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001599 OMPPrivateScope VarScope(*this);
1600 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001601 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001602 (void)VarScope.Privatize();
1603 EmitIgnoredExpr(F);
1604 }
1605 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001606 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001607 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001608 if (DoneBB)
1609 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001610}
1611
Alexander Musman515ad8c2014-05-22 08:54:05 +00001612void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001613 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001614 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001615 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001616 // for (IV in 0..LastIteration) BODY;
1617 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001618 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001619 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001620
Alexey Bataev62dbb972015-04-22 11:59:37 +00001621 // Emit: if (PreCond) - begin.
1622 // If the condition constant folds and can be elided, avoid emitting the
1623 // whole loop.
1624 bool CondConstant;
1625 llvm::BasicBlock *ContBlock = nullptr;
1626 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1627 if (!CondConstant)
1628 return;
1629 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001630 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1631 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001632 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1633 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001634 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001635 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001636 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001637
1638 // Emit the loop iteration variable.
1639 const Expr *IVExpr = S.getIterationVariable();
1640 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1641 CGF.EmitVarDecl(*IVDecl);
1642 CGF.EmitIgnoredExpr(S.getInit());
1643
1644 // Emit the iterations count variable.
1645 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001646 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001647 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1648 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1649 // Emit calculation of the iterations count.
1650 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001651 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001652
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001653 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001654
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001655 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001656 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001657 {
1658 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001659 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1660 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001661 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001662 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001663 bool HasLastprivateClause =
1664 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001665 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001666 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1667 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001668 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001669 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001670 CGF.EmitStopPoint(&S);
1671 },
1672 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001673 CGF.EmitOMPSimdFinal(
1674 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001675 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001676 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001677 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001678 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001679 emitPostUpdateForReductionClause(
1680 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001681 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001682 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001683 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001684 // Emit: if (PreCond) - end.
1685 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001686 CGF.EmitBranch(ContBlock);
1687 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001688 }
1689 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001690 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001691 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001692}
1693
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001694void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001695 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1696 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001697 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001698
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001699 const Expr *IVExpr = S.getIterationVariable();
1700 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1701 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1702
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001703 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1704
1705 // Start the loop with a block that tests the condition.
1706 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1707 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001708 const SourceRange &R = S.getSourceRange();
1709 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1710 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001711
1712 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001713 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001714 // UB = min(UB, GlobalUB)
1715 EmitIgnoredExpr(S.getEnsureUpperBound());
1716 // IV = LB
1717 EmitIgnoredExpr(S.getInit());
1718 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001719 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001720 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001721 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1722 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001723 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001724
1725 // If there are any cleanups between here and the loop-exit scope,
1726 // create a block to stage a loop exit along.
1727 auto ExitBlock = LoopExit.getBlock();
1728 if (LoopScope.requiresCleanups())
1729 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1730
1731 auto LoopBody = createBasicBlock("omp.dispatch.body");
1732 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1733 if (ExitBlock != LoopExit.getBlock()) {
1734 EmitBlock(ExitBlock);
1735 EmitBranchThroughCleanup(LoopExit);
1736 }
1737 EmitBlock(LoopBody);
1738
Alexander Musman92bdaab2015-03-12 13:37:50 +00001739 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1740 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001741 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001742 EmitIgnoredExpr(S.getInit());
1743
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001744 // Create a block for the increment.
1745 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1746 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1747
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001748 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1749 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001750 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1751 LoopStack.setParallel(!IsMonotonic);
1752 else
1753 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001754
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001755 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001756 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1757 [&S, LoopExit](CodeGenFunction &CGF) {
1758 CGF.EmitOMPLoopBody(S, LoopExit);
1759 CGF.EmitStopPoint(&S);
1760 },
1761 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1762 if (Ordered) {
1763 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1764 CGF, Loc, IVSize, IVSigned);
1765 }
1766 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001767
1768 EmitBlock(Continue.getBlock());
1769 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001770 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001771 // Emit "LB = LB + Stride", "UB = UB + Stride".
1772 EmitIgnoredExpr(S.getNextLowerBound());
1773 EmitIgnoredExpr(S.getNextUpperBound());
1774 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001775
1776 EmitBranch(CondBlock);
1777 LoopStack.pop();
1778 // Emit the fall-through block.
1779 EmitBlock(LoopExit.getBlock());
1780
1781 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001782 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1783 if (!DynamicOrOrdered)
1784 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1785 };
1786 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001787}
1788
1789void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001790 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001791 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1792 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1793 auto &RT = CGM.getOpenMPRuntime();
1794
1795 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001796 const bool DynamicOrOrdered =
1797 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001798
1799 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001800 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1801 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001802 "static non-chunked schedule does not need outer loop");
1803
1804 // Emit outer loop.
1805 //
1806 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1807 // When schedule(dynamic,chunk_size) is specified, the iterations are
1808 // distributed to threads in the team in chunks as the threads request them.
1809 // Each thread executes a chunk of iterations, then requests another chunk,
1810 // until no chunks remain to be distributed. Each chunk contains chunk_size
1811 // iterations, except for the last chunk to be distributed, which may have
1812 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1813 //
1814 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1815 // to threads in the team in chunks as the executing threads request them.
1816 // Each thread executes a chunk of iterations, then requests another chunk,
1817 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1818 // each chunk is proportional to the number of unassigned iterations divided
1819 // by the number of threads in the team, decreasing to 1. For a chunk_size
1820 // with value k (greater than 1), the size of each chunk is determined in the
1821 // same way, with the restriction that the chunks do not contain fewer than k
1822 // iterations (except for the last chunk to be assigned, which may have fewer
1823 // than k iterations).
1824 //
1825 // When schedule(auto) is specified, the decision regarding scheduling is
1826 // delegated to the compiler and/or runtime system. The programmer gives the
1827 // implementation the freedom to choose any possible mapping of iterations to
1828 // threads in the team.
1829 //
1830 // When schedule(runtime) is specified, the decision regarding scheduling is
1831 // deferred until run time, and the schedule and chunk size are taken from the
1832 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1833 // implementation defined
1834 //
1835 // while(__kmpc_dispatch_next(&LB, &UB)) {
1836 // idx = LB;
1837 // while (idx <= UB) { BODY; ++idx;
1838 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1839 // } // inner loop
1840 // }
1841 //
1842 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1843 // When schedule(static, chunk_size) is specified, iterations are divided into
1844 // chunks of size chunk_size, and the chunks are assigned to the threads in
1845 // the team in a round-robin fashion in the order of the thread number.
1846 //
1847 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1848 // while (idx <= UB) { BODY; ++idx; } // inner loop
1849 // LB = LB + ST;
1850 // UB = UB + ST;
1851 // }
1852 //
1853
1854 const Expr *IVExpr = S.getIterationVariable();
1855 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1856 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1857
1858 if (DynamicOrOrdered) {
1859 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001860 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1861 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001862 } else {
1863 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1864 Ordered, IL, LB, UB, ST, Chunk);
1865 }
1866
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001867 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001868 ST, IL, Chunk);
1869}
1870
1871void CodeGenFunction::EmitOMPDistributeOuterLoop(
1872 OpenMPDistScheduleClauseKind ScheduleKind,
1873 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1874 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1875
1876 auto &RT = CGM.getOpenMPRuntime();
1877
1878 // Emit outer loop.
1879 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1880 // dynamic
1881 //
1882
1883 const Expr *IVExpr = S.getIterationVariable();
1884 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1885 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1886
1887 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1888 IVSize, IVSigned, /* Ordered = */ false,
1889 IL, LB, UB, ST, Chunk);
1890
1891 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1892 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001893}
1894
Carlo Bertolli9925f152016-06-27 14:55:37 +00001895void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1896 const OMPDistributeParallelForDirective &S) {
1897 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1898 CGM.getOpenMPRuntime().emitInlinedDirective(
1899 *this, OMPD_distribute_parallel_for,
1900 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1901 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev957d8562016-11-17 15:12:05 +00001902 OMPCancelStackRAII CancelRegion(CGF, OMPD_distribute_parallel_for,
1903 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001904 CGF.EmitStmt(
1905 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1906 });
1907}
1908
Kelvin Li4a39add2016-07-05 05:00:15 +00001909void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1910 const OMPDistributeParallelForSimdDirective &S) {
1911 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1912 CGM.getOpenMPRuntime().emitInlinedDirective(
1913 *this, OMPD_distribute_parallel_for_simd,
1914 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1915 OMPLoopScope PreInitScope(CGF, S);
1916 CGF.EmitStmt(
1917 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1918 });
1919}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001920
1921void CodeGenFunction::EmitOMPDistributeSimdDirective(
1922 const OMPDistributeSimdDirective &S) {
1923 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1924 CGM.getOpenMPRuntime().emitInlinedDirective(
1925 *this, OMPD_distribute_simd,
1926 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1927 OMPLoopScope PreInitScope(CGF, S);
1928 CGF.EmitStmt(
1929 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1930 });
1931}
1932
Kelvin Lia579b912016-07-14 02:54:56 +00001933void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1934 const OMPTargetParallelForSimdDirective &S) {
1935 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1936 CGM.getOpenMPRuntime().emitInlinedDirective(
1937 *this, OMPD_target_parallel_for_simd,
1938 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1939 OMPLoopScope PreInitScope(CGF, S);
1940 CGF.EmitStmt(
1941 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1942 });
1943}
1944
Kelvin Li986330c2016-07-20 22:57:10 +00001945void CodeGenFunction::EmitOMPTargetSimdDirective(
1946 const OMPTargetSimdDirective &S) {
1947 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1948 CGM.getOpenMPRuntime().emitInlinedDirective(
1949 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1950 OMPLoopScope PreInitScope(CGF, S);
1951 CGF.EmitStmt(
1952 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1953 });
1954}
1955
Kelvin Li02532872016-08-05 14:37:37 +00001956void CodeGenFunction::EmitOMPTeamsDistributeDirective(
1957 const OMPTeamsDistributeDirective &S) {
1958 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1959 CGM.getOpenMPRuntime().emitInlinedDirective(
1960 *this, OMPD_teams_distribute,
1961 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1962 OMPLoopScope PreInitScope(CGF, S);
1963 CGF.EmitStmt(
1964 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1965 });
1966}
1967
Kelvin Li4e325f72016-10-25 12:50:55 +00001968void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
1969 const OMPTeamsDistributeSimdDirective &S) {
1970 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1971 CGM.getOpenMPRuntime().emitInlinedDirective(
1972 *this, OMPD_teams_distribute_simd,
1973 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1974 OMPLoopScope PreInitScope(CGF, S);
1975 CGF.EmitStmt(
1976 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1977 });
1978}
1979
Kelvin Li579e41c2016-11-30 23:51:03 +00001980void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
1981 const OMPTeamsDistributeParallelForSimdDirective &S) {
1982 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1983 CGM.getOpenMPRuntime().emitInlinedDirective(
1984 *this, OMPD_teams_distribute_parallel_for_simd,
1985 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1986 OMPLoopScope PreInitScope(CGF, S);
1987 CGF.EmitStmt(
1988 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1989 });
1990}
Kelvin Li4e325f72016-10-25 12:50:55 +00001991
Kelvin Li7ade93f2016-12-09 03:24:30 +00001992void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
1993 const OMPTeamsDistributeParallelForDirective &S) {
1994 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1995 CGM.getOpenMPRuntime().emitInlinedDirective(
1996 *this, OMPD_teams_distribute_parallel_for,
1997 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1998 OMPLoopScope PreInitScope(CGF, S);
1999 CGF.EmitStmt(
2000 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2001 });
2002}
2003
Kelvin Libf594a52016-12-17 05:48:59 +00002004void CodeGenFunction::EmitOMPTargetTeamsDirective(
2005 const OMPTargetTeamsDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002006 CGM.getOpenMPRuntime().emitInlinedDirective(
2007 *this, OMPD_target_teams, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2008 CGF.EmitStmt(
2009 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Libf594a52016-12-17 05:48:59 +00002010 });
2011}
2012
Kelvin Li83c451e2016-12-25 04:52:54 +00002013void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2014 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002015 CGM.getOpenMPRuntime().emitInlinedDirective(
2016 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002017 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002018 CGF.EmitStmt(
2019 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002020 });
2021}
2022
Kelvin Li80e8f562016-12-29 22:16:30 +00002023void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2024 const OMPTargetTeamsDistributeParallelForDirective &S) {
2025 CGM.getOpenMPRuntime().emitInlinedDirective(
2026 *this, OMPD_target_teams_distribute_parallel_for,
2027 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2028 CGF.EmitStmt(
2029 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2030 });
2031}
2032
Kelvin Li1851df52017-01-03 05:23:48 +00002033void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2034 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2035 CGM.getOpenMPRuntime().emitInlinedDirective(
2036 *this, OMPD_target_teams_distribute_parallel_for_simd,
2037 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2038 CGF.EmitStmt(
2039 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2040 });
2041}
2042
Kelvin Lida681182017-01-10 18:08:18 +00002043void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2044 const OMPTargetTeamsDistributeSimdDirective &S) {
2045 CGM.getOpenMPRuntime().emitInlinedDirective(
2046 *this, OMPD_target_teams_distribute_simd,
2047 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2048 CGF.EmitStmt(
2049 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2050 });
2051}
2052
Alexander Musmanc6388682014-12-15 07:07:06 +00002053/// \brief Emit a helper variable and return corresponding lvalue.
2054static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2055 const DeclRefExpr *Helper) {
2056 auto VDecl = cast<VarDecl>(Helper->getDecl());
2057 CGF.EmitVarDecl(*VDecl);
2058 return CGF.EmitLValue(Helper);
2059}
2060
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002061namespace {
2062 struct ScheduleKindModifiersTy {
2063 OpenMPScheduleClauseKind Kind;
2064 OpenMPScheduleClauseModifier M1;
2065 OpenMPScheduleClauseModifier M2;
2066 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2067 OpenMPScheduleClauseModifier M1,
2068 OpenMPScheduleClauseModifier M2)
2069 : Kind(Kind), M1(M1), M2(M2) {}
2070 };
2071} // namespace
2072
Alexey Bataev38e89532015-04-16 04:54:05 +00002073bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002074 // Emit the loop iteration variable.
2075 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2076 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2077 EmitVarDecl(*IVDecl);
2078
2079 // Emit the iterations count variable.
2080 // If it is not a variable, Sema decided to calculate iterations count on each
2081 // iteration (e.g., it is foldable into a constant).
2082 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2083 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2084 // Emit calculation of the iterations count.
2085 EmitIgnoredExpr(S.getCalcLastIteration());
2086 }
2087
2088 auto &RT = CGM.getOpenMPRuntime();
2089
Alexey Bataev38e89532015-04-16 04:54:05 +00002090 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002091 // Check pre-condition.
2092 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002093 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002094 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002095 // If the condition constant folds and can be elided, avoid emitting the
2096 // whole loop.
2097 bool CondConstant;
2098 llvm::BasicBlock *ContBlock = nullptr;
2099 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2100 if (!CondConstant)
2101 return false;
2102 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002103 auto *ThenBlock = createBasicBlock("omp.precond.then");
2104 ContBlock = createBasicBlock("omp.precond.end");
2105 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002106 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002107 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002108 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002109 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002110
Alexey Bataev8b427062016-05-25 12:36:08 +00002111 bool Ordered = false;
2112 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2113 if (OrderedClause->getNumForLoops())
2114 RT.emitDoacrossInit(*this, S);
2115 else
2116 Ordered = true;
2117 }
2118
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002119 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002120 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002121 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002122 // Emit helper vars inits.
2123 LValue LB =
2124 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2125 LValue UB =
2126 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2127 LValue ST =
2128 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2129 LValue IL =
2130 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2131
Alexander Musmanc6388682014-12-15 07:07:06 +00002132 // Emit 'then' code.
2133 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002134 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002135 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2136 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002137 // initialization of firstprivate variables and post-update of
2138 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002139 CGM.getOpenMPRuntime().emitBarrierCall(
2140 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2141 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002142 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002143 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002144 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002145 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002146 EmitOMPPrivateLoopCounters(S, LoopScope);
2147 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002148 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002149
2150 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002151 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002152 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002153 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002154 ScheduleKind.Schedule = C->getScheduleKind();
2155 ScheduleKind.M1 = C->getFirstScheduleModifier();
2156 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002157 if (const auto *Ch = C->getChunkSize()) {
2158 Chunk = EmitScalarExpr(Ch);
2159 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2160 S.getIterationVariable()->getType(),
2161 S.getLocStart());
2162 }
2163 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002164 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2165 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002166 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2167 // If the static schedule kind is specified or if the ordered clause is
2168 // specified, and if no monotonic modifier is specified, the effect will
2169 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002170 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002171 /* Chunked */ Chunk != nullptr) &&
2172 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002173 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2174 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002175 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2176 // When no chunk_size is specified, the iteration space is divided into
2177 // chunks that are approximately equal in size, and at most one chunk is
2178 // distributed to each thread. Note that the size of the chunks is
2179 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002180 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2181 IVSize, IVSigned, Ordered,
2182 IL.getAddress(), LB.getAddress(),
2183 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002184 auto LoopExit =
2185 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002186 // UB = min(UB, GlobalUB);
2187 EmitIgnoredExpr(S.getEnsureUpperBound());
2188 // IV = LB;
2189 EmitIgnoredExpr(S.getInit());
2190 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002191 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2192 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002193 [&S, LoopExit](CodeGenFunction &CGF) {
2194 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002195 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002196 },
2197 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002198 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002199 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002200 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2201 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2202 };
2203 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002204 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002205 const bool IsMonotonic =
2206 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2207 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2208 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2209 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002210 // Emit the outer loop, which requests its work chunk [LB..UB] from
2211 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002212 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002213 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2214 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002215 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002216 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2217 EmitOMPSimdFinal(S,
2218 [&](CodeGenFunction &CGF) -> llvm::Value * {
2219 return CGF.Builder.CreateIsNotNull(
2220 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2221 });
2222 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002223 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002224 // Emit post-update of the reduction variables if IsLastIter != 0.
2225 emitPostUpdateForReductionClause(
2226 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2227 return CGF.Builder.CreateIsNotNull(
2228 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2229 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002230 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2231 if (HasLastprivateClause)
2232 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002233 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2234 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002235 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002236 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002237 return CGF.Builder.CreateIsNotNull(
2238 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2239 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002240 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002241 if (ContBlock) {
2242 EmitBranch(ContBlock);
2243 EmitBlock(ContBlock, true);
2244 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002245 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002246 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002247}
2248
2249void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002250 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002251 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2252 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002253 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002254 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2255 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002256 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002257 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002258 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2259 S.hasCancel());
2260 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002261
2262 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002263 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002264 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2265 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002266}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002267
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002268void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002269 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002270 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2271 PrePostActionTy &) {
2272 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2273 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002274 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002275 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002276 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2277 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002278
2279 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002280 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002281 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2282 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002283}
2284
Alexey Bataev2df54a02015-03-12 08:53:29 +00002285static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2286 const Twine &Name,
2287 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002288 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002289 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002290 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002291 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002292}
2293
Alexey Bataev3392d762016-02-16 11:18:12 +00002294void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002295 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2296 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002297 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002298 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2299 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002300 auto &C = CGF.CGM.getContext();
2301 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2302 // Emit helper vars inits.
2303 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2304 CGF.Builder.getInt32(0));
2305 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2306 : CGF.Builder.getInt32(0);
2307 LValue UB =
2308 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2309 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2310 CGF.Builder.getInt32(1));
2311 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2312 CGF.Builder.getInt32(0));
2313 // Loop counter.
2314 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2315 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2316 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2317 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2318 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2319 // Generate condition for loop.
2320 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2321 OK_Ordinary, S.getLocStart(),
2322 /*fpContractable=*/false);
2323 // Increment for loop counter.
2324 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2325 S.getLocStart());
2326 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2327 // Iterate through all sections and emit a switch construct:
2328 // switch (IV) {
2329 // case 0:
2330 // <SectionStmt[0]>;
2331 // break;
2332 // ...
2333 // case <NumSection> - 1:
2334 // <SectionStmt[<NumSection> - 1]>;
2335 // break;
2336 // }
2337 // .omp.sections.exit:
2338 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2339 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2340 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2341 CS == nullptr ? 1 : CS->size());
2342 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002343 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002344 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002345 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2346 CGF.EmitBlock(CaseBB);
2347 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002348 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002349 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002350 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002351 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002352 } else {
2353 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2354 CGF.EmitBlock(CaseBB);
2355 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2356 CGF.EmitStmt(Stmt);
2357 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002358 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002359 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002360 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002361
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002362 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2363 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002364 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002365 // initialization of firstprivate variables and post-update of lastprivate
2366 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002367 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2368 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2369 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002370 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002371 CGF.EmitOMPPrivateClause(S, LoopScope);
2372 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2373 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2374 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002375
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002376 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002377 OpenMPScheduleTy ScheduleKind;
2378 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002379 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002380 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002381 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2382 UB.getAddress(), ST.getAddress());
2383 // UB = min(UB, GlobalUB);
2384 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2385 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2386 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2387 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2388 // IV = LB;
2389 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2390 // while (idx <= UB) { BODY; ++idx; }
2391 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2392 [](CodeGenFunction &) {});
2393 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002394 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2395 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2396 };
2397 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002398 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002399 // Emit post-update of the reduction variables if IsLastIter != 0.
2400 emitPostUpdateForReductionClause(
2401 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2402 return CGF.Builder.CreateIsNotNull(
2403 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2404 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002405
2406 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2407 if (HasLastprivates)
2408 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002409 S, /*NoFinals=*/false,
2410 CGF.Builder.CreateIsNotNull(
2411 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002412 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002413
2414 bool HasCancel = false;
2415 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2416 HasCancel = OSD->hasCancel();
2417 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2418 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002419 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002420 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2421 HasCancel);
2422 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2423 // clause. Otherwise the barrier will be generated by the codegen for the
2424 // directive.
2425 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002426 // Emit implicit barrier to synchronize threads and avoid data races on
2427 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002428 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2429 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002430 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002431}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002432
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002433void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002434 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002435 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002436 EmitSections(S);
2437 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002438 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002439 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002440 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2441 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002442 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002443}
2444
2445void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002446 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002447 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002448 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002449 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002450 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2451 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002452}
2453
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002454void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002455 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002456 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002457 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002458 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002459 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002460 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002461 // Build a list of copyprivate variables along with helper expressions
2462 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002463 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002464 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002465 DestExprs.append(C->destination_exprs().begin(),
2466 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002467 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002468 AssignmentOps.append(C->assignment_ops().begin(),
2469 C->assignment_ops().end());
2470 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002471 // Emit code for 'single' region along with 'copyprivate' clauses
2472 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2473 Action.Enter(CGF);
2474 OMPPrivateScope SingleScope(CGF);
2475 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2476 CGF.EmitOMPPrivateClause(S, SingleScope);
2477 (void)SingleScope.Privatize();
2478 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2479 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002480 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002481 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002482 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2483 CopyprivateVars, DestExprs,
2484 SrcExprs, AssignmentOps);
2485 }
2486 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2487 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002488 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002489 CGM.getOpenMPRuntime().emitBarrierCall(
2490 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002491 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002492 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002493}
2494
Alexey Bataev8d690652014-12-04 07:23:53 +00002495void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002496 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2497 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002498 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002499 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002500 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002501 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002502}
2503
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002504void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002505 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2506 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002507 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002508 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002509 Expr *Hint = nullptr;
2510 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2511 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002512 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002513 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2514 S.getDirectiveName().getAsString(),
2515 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002516}
2517
Alexey Bataev671605e2015-04-13 05:28:11 +00002518void CodeGenFunction::EmitOMPParallelForDirective(
2519 const OMPParallelForDirective &S) {
2520 // Emit directive as a combined directive that consists of two implicit
2521 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002522 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002523 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Alexey Bataev671605e2015-04-13 05:28:11 +00002524 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002525 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002526 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002527}
2528
Alexander Musmane4e893b2014-09-23 09:33:00 +00002529void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002530 const OMPParallelForSimdDirective &S) {
2531 // Emit directive as a combined directive that consists of two implicit
2532 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002533 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002534 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002535 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002536 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002537}
2538
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002539void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002540 const OMPParallelSectionsDirective &S) {
2541 // Emit directive as a combined directive that consists of two implicit
2542 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002543 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2544 CGF.EmitSections(S);
2545 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002546 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002547}
2548
Alexey Bataev7292c292016-04-25 12:22:29 +00002549void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2550 const RegionCodeGenTy &BodyGen,
2551 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002552 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002553 // Emit outlined function for task construct.
2554 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002555 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002556 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002557 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002558 // Check if the task is final
2559 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2560 // If the condition constant folds and can be elided, try to avoid emitting
2561 // the condition and the dead arm of the if/else.
2562 auto *Cond = Clause->getCondition();
2563 bool CondConstant;
2564 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2565 Data.Final.setInt(CondConstant);
2566 else
2567 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2568 } else {
2569 // By default the task is not final.
2570 Data.Final.setInt(/*IntVal=*/false);
2571 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002572 // Check if the task has 'priority' clause.
2573 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002574 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002575 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002576 Data.Priority.setPointer(EmitScalarConversion(
2577 EmitScalarExpr(Prio), Prio->getType(),
2578 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2579 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002580 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002581 // The first function argument for tasks is a thread id, the second one is a
2582 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002583 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2584 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002585 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002586 auto IRef = C->varlist_begin();
2587 for (auto *IInit : C->private_copies()) {
2588 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2589 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002590 Data.PrivateVars.push_back(*IRef);
2591 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002592 }
2593 ++IRef;
2594 }
2595 }
2596 EmittedAsPrivate.clear();
2597 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002598 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002599 auto IRef = C->varlist_begin();
2600 auto IElemInitRef = C->inits().begin();
2601 for (auto *IInit : C->private_copies()) {
2602 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2603 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002604 Data.FirstprivateVars.push_back(*IRef);
2605 Data.FirstprivateCopies.push_back(IInit);
2606 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002607 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002608 ++IRef;
2609 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002610 }
2611 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002612 // Get list of lastprivate variables (for taskloops).
2613 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2614 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2615 auto IRef = C->varlist_begin();
2616 auto ID = C->destination_exprs().begin();
2617 for (auto *IInit : C->private_copies()) {
2618 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2619 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2620 Data.LastprivateVars.push_back(*IRef);
2621 Data.LastprivateCopies.push_back(IInit);
2622 }
2623 LastprivateDstsOrigs.insert(
2624 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2625 cast<DeclRefExpr>(*IRef)});
2626 ++IRef;
2627 ++ID;
2628 }
2629 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002630 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002631 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2632 for (auto *IRef : C->varlists())
2633 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00002634 auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002635 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002636 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002637 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002638 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2639 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002640 auto *CopyFn = CGF.Builder.CreateLoad(
2641 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2642 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2643 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2644 // Map privates.
2645 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2646 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2647 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002648 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002649 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2650 Address PrivatePtr = CGF.CreateMemTemp(
2651 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2652 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2653 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002654 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002655 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002656 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2657 Address PrivatePtr =
2658 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2659 ".firstpriv.ptr.addr");
2660 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2661 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002662 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002663 for (auto *E : Data.LastprivateVars) {
2664 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2665 Address PrivatePtr =
2666 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2667 ".lastpriv.ptr.addr");
2668 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2669 CallArgs.push_back(PrivatePtr.getPointer());
2670 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002671 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002672 for (auto &&Pair : LastprivateDstsOrigs) {
2673 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2674 DeclRefExpr DRE(
2675 const_cast<VarDecl *>(OrigVD),
2676 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2677 OrigVD) != nullptr,
2678 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2679 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2680 return CGF.EmitLValue(&DRE).getAddress();
2681 });
2682 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002683 for (auto &&Pair : PrivatePtrs) {
2684 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2685 CGF.getContext().getDeclAlign(Pair.first));
2686 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2687 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002688 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002689 (void)Scope.Privatize();
2690
2691 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002692 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002693 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002694 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2695 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2696 Data.NumberOfParts);
2697 OMPLexicalScope Scope(*this, S);
2698 TaskGen(*this, OutlinedFn, Data);
2699}
2700
2701void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2702 // Emit outlined function for task construct.
2703 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2704 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002705 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002706 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002707 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2708 if (C->getNameModifier() == OMPD_unknown ||
2709 C->getNameModifier() == OMPD_task) {
2710 IfCond = C->getCondition();
2711 break;
2712 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002713 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002714
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002715 OMPTaskDataTy Data;
2716 // Check if we should emit tied or untied task.
2717 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002718 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2719 CGF.EmitStmt(CS->getCapturedStmt());
2720 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002721 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002722 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002723 const OMPTaskDataTy &Data) {
2724 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2725 SharedsTy, CapturedStruct, IfCond,
2726 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002727 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002728 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002729}
2730
Alexey Bataev9f797f32015-02-05 05:57:51 +00002731void CodeGenFunction::EmitOMPTaskyieldDirective(
2732 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002733 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002734}
2735
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002736void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002737 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002738}
2739
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002740void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2741 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002742}
2743
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002744void CodeGenFunction::EmitOMPTaskgroupDirective(
2745 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002746 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2747 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002748 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002749 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002750 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002751 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2752}
2753
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002754void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002755 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002756 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002757 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2758 FlushClause->varlist_end());
2759 }
2760 return llvm::None;
2761 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002762}
2763
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002764void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2765 // Emit the loop iteration variable.
2766 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2767 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2768 EmitVarDecl(*IVDecl);
2769
2770 // Emit the iterations count variable.
2771 // If it is not a variable, Sema decided to calculate iterations count on each
2772 // iteration (e.g., it is foldable into a constant).
2773 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2774 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2775 // Emit calculation of the iterations count.
2776 EmitIgnoredExpr(S.getCalcLastIteration());
2777 }
2778
2779 auto &RT = CGM.getOpenMPRuntime();
2780
Carlo Bertolli962bb802017-01-03 18:24:42 +00002781 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002782 // Check pre-condition.
2783 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002784 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002785 // Skip the entire loop if we don't meet the precondition.
2786 // If the condition constant folds and can be elided, avoid emitting the
2787 // whole loop.
2788 bool CondConstant;
2789 llvm::BasicBlock *ContBlock = nullptr;
2790 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2791 if (!CondConstant)
2792 return;
2793 } else {
2794 auto *ThenBlock = createBasicBlock("omp.precond.then");
2795 ContBlock = createBasicBlock("omp.precond.end");
2796 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2797 getProfileCount(&S));
2798 EmitBlock(ThenBlock);
2799 incrementProfileCounter(&S);
2800 }
2801
2802 // Emit 'then' code.
2803 {
2804 // Emit helper vars inits.
2805 LValue LB =
2806 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2807 LValue UB =
2808 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2809 LValue ST =
2810 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2811 LValue IL =
2812 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2813
2814 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00002815 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2816 // Emit implicit barrier to synchronize threads and avoid data races on
2817 // initialization of firstprivate variables and post-update of
2818 // lastprivate variables.
2819 CGM.getOpenMPRuntime().emitBarrierCall(
2820 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2821 /*ForceSimpleCall=*/true);
2822 }
2823 EmitOMPPrivateClause(S, LoopScope);
2824 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002825 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002826 (void)LoopScope.Privatize();
2827
2828 // Detect the distribute schedule kind and chunk.
2829 llvm::Value *Chunk = nullptr;
2830 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2831 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2832 ScheduleKind = C->getDistScheduleKind();
2833 if (const auto *Ch = C->getChunkSize()) {
2834 Chunk = EmitScalarExpr(Ch);
2835 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2836 S.getIterationVariable()->getType(),
2837 S.getLocStart());
2838 }
2839 }
2840 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2841 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2842
2843 // OpenMP [2.10.8, distribute Construct, Description]
2844 // If dist_schedule is specified, kind must be static. If specified,
2845 // iterations are divided into chunks of size chunk_size, chunks are
2846 // assigned to the teams of the league in a round-robin fashion in the
2847 // order of the team number. When no chunk_size is specified, the
2848 // iteration space is divided into chunks that are approximately equal
2849 // in size, and at most one chunk is distributed to each team of the
2850 // league. The size of the chunks is unspecified in this case.
2851 if (RT.isStaticNonchunked(ScheduleKind,
2852 /* Chunked */ Chunk != nullptr)) {
2853 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2854 IVSize, IVSigned, /* Ordered = */ false,
2855 IL.getAddress(), LB.getAddress(),
2856 UB.getAddress(), ST.getAddress());
2857 auto LoopExit =
2858 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2859 // UB = min(UB, GlobalUB);
2860 EmitIgnoredExpr(S.getEnsureUpperBound());
2861 // IV = LB;
2862 EmitIgnoredExpr(S.getInit());
2863 // while (idx <= UB) { BODY; ++idx; }
2864 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2865 S.getInc(),
2866 [&S, LoopExit](CodeGenFunction &CGF) {
2867 CGF.EmitOMPLoopBody(S, LoopExit);
2868 CGF.EmitStopPoint(&S);
2869 },
2870 [](CodeGenFunction &) {});
2871 EmitBlock(LoopExit.getBlock());
2872 // Tell the runtime we are done.
2873 RT.emitForStaticFinish(*this, S.getLocStart());
2874 } else {
2875 // Emit the outer loop, which requests its work chunk [LB..UB] from
2876 // runtime and runs the inner loop to process it.
2877 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2878 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2879 IL.getAddress(), Chunk);
2880 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00002881
2882 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2883 if (HasLastprivateClause)
2884 EmitOMPLastprivateClauseFinal(
2885 S, /*NoFinals=*/false,
2886 Builder.CreateIsNotNull(
2887 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002888 }
2889
2890 // We're now done with the loop, so jump to the continuation block.
2891 if (ContBlock) {
2892 EmitBranch(ContBlock);
2893 EmitBlock(ContBlock, true);
2894 }
2895 }
2896}
2897
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002898void CodeGenFunction::EmitOMPDistributeDirective(
2899 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002900 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002901 CGF.EmitOMPDistributeLoop(S);
2902 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002903 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002904 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2905 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002906}
2907
Alexey Bataev5f600d62015-09-29 03:48:57 +00002908static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2909 const CapturedStmt *S) {
2910 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2911 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2912 CGF.CapturedStmtInfo = &CapStmtInfo;
2913 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2914 Fn->addFnAttr(llvm::Attribute::NoInline);
2915 return Fn;
2916}
2917
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002918void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002919 if (!S.getAssociatedStmt()) {
2920 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
2921 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00002922 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00002923 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002924 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002925 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2926 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002927 if (C) {
2928 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2929 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2930 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2931 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2932 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2933 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002934 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002935 CGF.EmitStmt(
2936 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2937 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002938 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002939 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002940 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002941}
2942
Alexey Bataevb57056f2015-01-22 06:17:56 +00002943static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002944 QualType SrcType, QualType DestType,
2945 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002946 assert(CGF.hasScalarEvaluationKind(DestType) &&
2947 "DestType must have scalar evaluation kind.");
2948 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2949 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002950 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2951 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002952 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002953 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002954}
2955
2956static CodeGenFunction::ComplexPairTy
2957convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002958 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002959 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2960 "DestType must have complex evaluation kind.");
2961 CodeGenFunction::ComplexPairTy ComplexVal;
2962 if (Val.isScalar()) {
2963 // Convert the input element to the element type of the complex.
2964 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002965 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2966 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002967 ComplexVal = CodeGenFunction::ComplexPairTy(
2968 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2969 } else {
2970 assert(Val.isComplex() && "Must be a scalar or complex.");
2971 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2972 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2973 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002974 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002975 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002976 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002977 }
2978 return ComplexVal;
2979}
2980
Alexey Bataev5e018f92015-04-23 06:35:10 +00002981static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2982 LValue LVal, RValue RVal) {
2983 if (LVal.isGlobalReg()) {
2984 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2985 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002986 CGF.EmitAtomicStore(RVal, LVal,
2987 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2988 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002989 LVal.isVolatile(), /*IsInit=*/false);
2990 }
2991}
2992
Alexey Bataev8524d152016-01-21 12:35:58 +00002993void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2994 QualType RValTy, SourceLocation Loc) {
2995 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002996 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002997 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2998 *this, RVal, RValTy, LVal.getType(), Loc)),
2999 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003000 break;
3001 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003002 EmitStoreOfComplex(
3003 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003004 /*isInit=*/false);
3005 break;
3006 case TEK_Aggregate:
3007 llvm_unreachable("Must be a scalar or complex.");
3008 }
3009}
3010
Alexey Bataevb57056f2015-01-22 06:17:56 +00003011static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3012 const Expr *X, const Expr *V,
3013 SourceLocation Loc) {
3014 // v = x;
3015 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3016 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3017 LValue XLValue = CGF.EmitLValue(X);
3018 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003019 RValue Res = XLValue.isGlobalReg()
3020 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003021 : CGF.EmitAtomicLoad(
3022 XLValue, Loc,
3023 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3024 : llvm::AtomicOrdering::Monotonic,
3025 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003026 // OpenMP, 2.12.6, atomic Construct
3027 // Any atomic construct with a seq_cst clause forces the atomically
3028 // performed operation to include an implicit flush operation without a
3029 // list.
3030 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003031 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003032 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003033}
3034
Alexey Bataevb8329262015-02-27 06:33:30 +00003035static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3036 const Expr *X, const Expr *E,
3037 SourceLocation Loc) {
3038 // x = expr;
3039 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003040 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003041 // OpenMP, 2.12.6, atomic Construct
3042 // Any atomic construct with a seq_cst clause forces the atomically
3043 // performed operation to include an implicit flush operation without a
3044 // list.
3045 if (IsSeqCst)
3046 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3047}
3048
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003049static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3050 RValue Update,
3051 BinaryOperatorKind BO,
3052 llvm::AtomicOrdering AO,
3053 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003054 auto &Context = CGF.CGM.getContext();
3055 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003056 // expression is simple and atomic is allowed for the given type for the
3057 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003058 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003059 !Update.getScalarVal()->getType()->isIntegerTy() ||
3060 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3061 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003062 X.getAddress().getElementType())) ||
3063 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003064 !Context.getTargetInfo().hasBuiltinAtomic(
3065 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003066 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003067
3068 llvm::AtomicRMWInst::BinOp RMWOp;
3069 switch (BO) {
3070 case BO_Add:
3071 RMWOp = llvm::AtomicRMWInst::Add;
3072 break;
3073 case BO_Sub:
3074 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003075 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003076 RMWOp = llvm::AtomicRMWInst::Sub;
3077 break;
3078 case BO_And:
3079 RMWOp = llvm::AtomicRMWInst::And;
3080 break;
3081 case BO_Or:
3082 RMWOp = llvm::AtomicRMWInst::Or;
3083 break;
3084 case BO_Xor:
3085 RMWOp = llvm::AtomicRMWInst::Xor;
3086 break;
3087 case BO_LT:
3088 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3089 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3090 : llvm::AtomicRMWInst::Max)
3091 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3092 : llvm::AtomicRMWInst::UMax);
3093 break;
3094 case BO_GT:
3095 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3096 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3097 : llvm::AtomicRMWInst::Min)
3098 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3099 : llvm::AtomicRMWInst::UMin);
3100 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003101 case BO_Assign:
3102 RMWOp = llvm::AtomicRMWInst::Xchg;
3103 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003104 case BO_Mul:
3105 case BO_Div:
3106 case BO_Rem:
3107 case BO_Shl:
3108 case BO_Shr:
3109 case BO_LAnd:
3110 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003111 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003112 case BO_PtrMemD:
3113 case BO_PtrMemI:
3114 case BO_LE:
3115 case BO_GE:
3116 case BO_EQ:
3117 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003118 case BO_AddAssign:
3119 case BO_SubAssign:
3120 case BO_AndAssign:
3121 case BO_OrAssign:
3122 case BO_XorAssign:
3123 case BO_MulAssign:
3124 case BO_DivAssign:
3125 case BO_RemAssign:
3126 case BO_ShlAssign:
3127 case BO_ShrAssign:
3128 case BO_Comma:
3129 llvm_unreachable("Unsupported atomic update operation");
3130 }
3131 auto *UpdateVal = Update.getScalarVal();
3132 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3133 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003134 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003135 X.getType()->hasSignedIntegerRepresentation());
3136 }
John McCall7f416cc2015-09-08 08:05:57 +00003137 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003138 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003139}
3140
Alexey Bataev5e018f92015-04-23 06:35:10 +00003141std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003142 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3143 llvm::AtomicOrdering AO, SourceLocation Loc,
3144 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3145 // Update expressions are allowed to have the following forms:
3146 // x binop= expr; -> xrval + expr;
3147 // x++, ++x -> xrval + 1;
3148 // x--, --x -> xrval - 1;
3149 // x = x binop expr; -> xrval binop expr
3150 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003151 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3152 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003153 if (X.isGlobalReg()) {
3154 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3155 // 'xrval'.
3156 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3157 } else {
3158 // Perform compare-and-swap procedure.
3159 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003160 }
3161 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003162 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003163}
3164
3165static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3166 const Expr *X, const Expr *E,
3167 const Expr *UE, bool IsXLHSInRHSPart,
3168 SourceLocation Loc) {
3169 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3170 "Update expr in 'atomic update' must be a binary operator.");
3171 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3172 // Update expressions are allowed to have the following forms:
3173 // x binop= expr; -> xrval + expr;
3174 // x++, ++x -> xrval + 1;
3175 // x--, --x -> xrval - 1;
3176 // x = x binop expr; -> xrval binop expr
3177 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003178 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003179 LValue XLValue = CGF.EmitLValue(X);
3180 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003181 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3182 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003183 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3184 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3185 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3186 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3187 auto Gen =
3188 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3189 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3190 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3191 return CGF.EmitAnyExpr(UE);
3192 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003193 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3194 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3195 // OpenMP, 2.12.6, atomic Construct
3196 // Any atomic construct with a seq_cst clause forces the atomically
3197 // performed operation to include an implicit flush operation without a
3198 // list.
3199 if (IsSeqCst)
3200 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3201}
3202
3203static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003204 QualType SourceType, QualType ResType,
3205 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003206 switch (CGF.getEvaluationKind(ResType)) {
3207 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003208 return RValue::get(
3209 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003210 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003211 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003212 return RValue::getComplex(Res.first, Res.second);
3213 }
3214 case TEK_Aggregate:
3215 break;
3216 }
3217 llvm_unreachable("Must be a scalar or complex.");
3218}
3219
3220static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3221 bool IsPostfixUpdate, const Expr *V,
3222 const Expr *X, const Expr *E,
3223 const Expr *UE, bool IsXLHSInRHSPart,
3224 SourceLocation Loc) {
3225 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3226 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3227 RValue NewVVal;
3228 LValue VLValue = CGF.EmitLValue(V);
3229 LValue XLValue = CGF.EmitLValue(X);
3230 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003231 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3232 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003233 QualType NewVValType;
3234 if (UE) {
3235 // 'x' is updated with some additional value.
3236 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3237 "Update expr in 'atomic capture' must be a binary operator.");
3238 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3239 // Update expressions are allowed to have the following forms:
3240 // x binop= expr; -> xrval + expr;
3241 // x++, ++x -> xrval + 1;
3242 // x--, --x -> xrval - 1;
3243 // x = x binop expr; -> xrval binop expr
3244 // x = expr Op x; - > expr binop xrval;
3245 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3246 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3247 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3248 NewVValType = XRValExpr->getType();
3249 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3250 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003251 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003252 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3253 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3254 RValue Res = CGF.EmitAnyExpr(UE);
3255 NewVVal = IsPostfixUpdate ? XRValue : Res;
3256 return Res;
3257 };
3258 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3259 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3260 if (Res.first) {
3261 // 'atomicrmw' instruction was generated.
3262 if (IsPostfixUpdate) {
3263 // Use old value from 'atomicrmw'.
3264 NewVVal = Res.second;
3265 } else {
3266 // 'atomicrmw' does not provide new value, so evaluate it using old
3267 // value of 'x'.
3268 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3269 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3270 NewVVal = CGF.EmitAnyExpr(UE);
3271 }
3272 }
3273 } else {
3274 // 'x' is simply rewritten with some 'expr'.
3275 NewVValType = X->getType().getNonReferenceType();
3276 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003277 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003278 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003279 NewVVal = XRValue;
3280 return ExprRValue;
3281 };
3282 // Try to perform atomicrmw xchg, otherwise simple exchange.
3283 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3284 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3285 Loc, Gen);
3286 if (Res.first) {
3287 // 'atomicrmw' instruction was generated.
3288 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3289 }
3290 }
3291 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003292 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003293 // OpenMP, 2.12.6, atomic Construct
3294 // Any atomic construct with a seq_cst clause forces the atomically
3295 // performed operation to include an implicit flush operation without a
3296 // list.
3297 if (IsSeqCst)
3298 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3299}
3300
Alexey Bataevb57056f2015-01-22 06:17:56 +00003301static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003302 bool IsSeqCst, bool IsPostfixUpdate,
3303 const Expr *X, const Expr *V, const Expr *E,
3304 const Expr *UE, bool IsXLHSInRHSPart,
3305 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003306 switch (Kind) {
3307 case OMPC_read:
3308 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3309 break;
3310 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003311 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3312 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003313 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003314 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003315 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3316 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003317 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003318 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3319 IsXLHSInRHSPart, Loc);
3320 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003321 case OMPC_if:
3322 case OMPC_final:
3323 case OMPC_num_threads:
3324 case OMPC_private:
3325 case OMPC_firstprivate:
3326 case OMPC_lastprivate:
3327 case OMPC_reduction:
3328 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003329 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003330 case OMPC_collapse:
3331 case OMPC_default:
3332 case OMPC_seq_cst:
3333 case OMPC_shared:
3334 case OMPC_linear:
3335 case OMPC_aligned:
3336 case OMPC_copyin:
3337 case OMPC_copyprivate:
3338 case OMPC_flush:
3339 case OMPC_proc_bind:
3340 case OMPC_schedule:
3341 case OMPC_ordered:
3342 case OMPC_nowait:
3343 case OMPC_untied:
3344 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003345 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003346 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003347 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003348 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003349 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003350 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003351 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003352 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003353 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003354 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003355 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003356 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003357 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003358 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003359 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003360 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003361 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003362 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003363 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003364 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003365 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3366 }
3367}
3368
3369void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003370 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003371 OpenMPClauseKind Kind = OMPC_unknown;
3372 for (auto *C : S.clauses()) {
3373 // Find first clause (skip seq_cst clause, if it is first).
3374 if (C->getClauseKind() != OMPC_seq_cst) {
3375 Kind = C->getClauseKind();
3376 break;
3377 }
3378 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003379
3380 const auto *CS =
3381 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003382 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003383 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003384 }
3385 // Processing for statements under 'atomic capture'.
3386 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3387 for (const auto *C : Compound->body()) {
3388 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3389 enterFullExpression(EWC);
3390 }
3391 }
3392 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003393
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003394 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3395 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003396 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003397 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3398 S.getV(), S.getExpr(), S.getUpdateExpr(),
3399 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003400 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003401 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003402 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003403}
3404
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003405static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3406 const OMPExecutableDirective &S,
3407 const RegionCodeGenTy &CodeGen) {
3408 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3409 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003410 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3411
3412 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003413 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003414
Samuel Antaoee8fb302016-01-06 13:42:12 +00003415 llvm::Function *Fn = nullptr;
3416 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003417
3418 // Check if we have any if clause associated with the directive.
3419 const Expr *IfCond = nullptr;
3420
3421 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3422 IfCond = C->getCondition();
3423 }
3424
3425 // Check if we have any device clause associated with the directive.
3426 const Expr *Device = nullptr;
3427 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3428 Device = C->getDevice();
3429 }
3430
Samuel Antaoee8fb302016-01-06 13:42:12 +00003431 // Check if we have an if clause whose conditional always evaluates to false
3432 // or if we do not have any targets specified. If so the target region is not
3433 // an offload entry point.
3434 bool IsOffloadEntry = true;
3435 if (IfCond) {
3436 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003437 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003438 IsOffloadEntry = false;
3439 }
3440 if (CGM.getLangOpts().OMPTargetTriples.empty())
3441 IsOffloadEntry = false;
3442
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003443 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003444 StringRef ParentName;
3445 // In case we have Ctors/Dtors we use the complete type variant to produce
3446 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003447 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003448 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003449 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003450 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3451 else
3452 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003453 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003455 // Emit target region as a standalone region.
3456 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3457 IsOffloadEntry, CodeGen);
3458 OMPLexicalScope Scope(CGF, S);
3459 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003460 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003461}
3462
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003463static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3464 PrePostActionTy &Action) {
3465 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3466 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3467 CGF.EmitOMPPrivateClause(S, PrivateScope);
3468 (void)PrivateScope.Privatize();
3469
3470 Action.Enter(CGF);
3471 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3472}
3473
3474void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3475 StringRef ParentName,
3476 const OMPTargetDirective &S) {
3477 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3478 emitTargetRegion(CGF, S, Action);
3479 };
3480 llvm::Function *Fn;
3481 llvm::Constant *Addr;
3482 // Emit target region as a standalone region.
3483 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3484 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3485 assert(Fn && Addr && "Target device function emission failed.");
3486}
3487
3488void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3489 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3490 emitTargetRegion(CGF, S, Action);
3491 };
3492 emitCommonOMPTargetDirective(*this, S, CodeGen);
3493}
3494
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003495static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3496 const OMPExecutableDirective &S,
3497 OpenMPDirectiveKind InnermostKind,
3498 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003499 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3500 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3501 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003502
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003503 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3504 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3505 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3506 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003507 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3508 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003509
Carlo Bertollic6872252016-04-04 15:55:02 +00003510 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3511 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003512 }
3513
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003514 OMPLexicalScope Scope(CGF, S);
3515 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3516 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003517 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3518 CapturedVars);
3519}
3520
3521void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003522 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003523 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003524 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003525 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3526 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003527 (void)PrivateScope.Privatize();
3528 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3529 };
3530 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003531}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003532
3533void CodeGenFunction::EmitOMPCancellationPointDirective(
3534 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003535 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3536 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003537}
3538
Alexey Bataev80909872015-07-02 11:25:17 +00003539void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003540 const Expr *IfCond = nullptr;
3541 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3542 if (C->getNameModifier() == OMPD_unknown ||
3543 C->getNameModifier() == OMPD_cancel) {
3544 IfCond = C->getCondition();
3545 break;
3546 }
3547 }
3548 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003549 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003550}
3551
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003552CodeGenFunction::JumpDest
3553CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003554 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3555 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003556 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003557 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003558 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3559 Kind == OMPD_distribute_parallel_for ||
3560 Kind == OMPD_target_parallel_for);
3561 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003562}
Michael Wong65f367f2015-07-21 13:44:28 +00003563
Samuel Antaocc10b852016-07-28 14:23:26 +00003564void CodeGenFunction::EmitOMPUseDevicePtrClause(
3565 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3566 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3567 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3568 auto OrigVarIt = C.varlist_begin();
3569 auto InitIt = C.inits().begin();
3570 for (auto PvtVarIt : C.private_copies()) {
3571 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3572 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3573 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3574
3575 // In order to identify the right initializer we need to match the
3576 // declaration used by the mapping logic. In some cases we may get
3577 // OMPCapturedExprDecl that refers to the original declaration.
3578 const ValueDecl *MatchingVD = OrigVD;
3579 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3580 // OMPCapturedExprDecl are used to privative fields of the current
3581 // structure.
3582 auto *ME = cast<MemberExpr>(OED->getInit());
3583 assert(isa<CXXThisExpr>(ME->getBase()) &&
3584 "Base should be the current struct!");
3585 MatchingVD = ME->getMemberDecl();
3586 }
3587
3588 // If we don't have information about the current list item, move on to
3589 // the next one.
3590 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3591 if (InitAddrIt == CaptureDeviceAddrMap.end())
3592 continue;
3593
3594 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3595 // Initialize the temporary initialization variable with the address we
3596 // get from the runtime library. We have to cast the source address
3597 // because it is always a void *. References are materialized in the
3598 // privatization scope, so the initialization here disregards the fact
3599 // the original variable is a reference.
3600 QualType AddrQTy =
3601 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3602 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3603 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3604 setAddrOfLocalVar(InitVD, InitAddr);
3605
3606 // Emit private declaration, it will be initialized by the value we
3607 // declaration we just added to the local declarations map.
3608 EmitDecl(*PvtVD);
3609
3610 // The initialization variables reached its purpose in the emission
3611 // ofthe previous declaration, so we don't need it anymore.
3612 LocalDeclMap.erase(InitVD);
3613
3614 // Return the address of the private variable.
3615 return GetAddrOfLocalVar(PvtVD);
3616 });
3617 assert(IsRegistered && "firstprivate var already registered as private");
3618 // Silence the warning about unused variable.
3619 (void)IsRegistered;
3620
3621 ++OrigVarIt;
3622 ++InitIt;
3623 }
3624}
3625
Michael Wong65f367f2015-07-21 13:44:28 +00003626// Generate the instructions for '#pragma omp target data' directive.
3627void CodeGenFunction::EmitOMPTargetDataDirective(
3628 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003629 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3630
3631 // Create a pre/post action to signal the privatization of the device pointer.
3632 // This action can be replaced by the OpenMP runtime code generation to
3633 // deactivate privatization.
3634 bool PrivatizeDevicePointers = false;
3635 class DevicePointerPrivActionTy : public PrePostActionTy {
3636 bool &PrivatizeDevicePointers;
3637
3638 public:
3639 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3640 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3641 void Enter(CodeGenFunction &CGF) override {
3642 PrivatizeDevicePointers = true;
3643 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003644 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003645 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3646
3647 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3648 CodeGenFunction &CGF, PrePostActionTy &Action) {
3649 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3650 CGF.EmitStmt(
3651 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3652 };
3653
3654 // Codegen that selects wheather to generate the privatization code or not.
3655 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3656 &InnermostCodeGen](CodeGenFunction &CGF,
3657 PrePostActionTy &Action) {
3658 RegionCodeGenTy RCG(InnermostCodeGen);
3659 PrivatizeDevicePointers = false;
3660
3661 // Call the pre-action to change the status of PrivatizeDevicePointers if
3662 // needed.
3663 Action.Enter(CGF);
3664
3665 if (PrivatizeDevicePointers) {
3666 OMPPrivateScope PrivateScope(CGF);
3667 // Emit all instances of the use_device_ptr clause.
3668 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3669 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3670 Info.CaptureDeviceAddrMap);
3671 (void)PrivateScope.Privatize();
3672 RCG(CGF);
3673 } else
3674 RCG(CGF);
3675 };
3676
3677 // Forward the provided action to the privatization codegen.
3678 RegionCodeGenTy PrivRCG(PrivCodeGen);
3679 PrivRCG.setAction(Action);
3680
3681 // Notwithstanding the body of the region is emitted as inlined directive,
3682 // we don't use an inline scope as changes in the references inside the
3683 // region are expected to be visible outside, so we do not privative them.
3684 OMPLexicalScope Scope(CGF, S);
3685 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3686 PrivRCG);
3687 };
3688
3689 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003690
3691 // If we don't have target devices, don't bother emitting the data mapping
3692 // code.
3693 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003694 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003695 return;
3696 }
3697
3698 // Check if we have any if clause associated with the directive.
3699 const Expr *IfCond = nullptr;
3700 if (auto *C = S.getSingleClause<OMPIfClause>())
3701 IfCond = C->getCondition();
3702
3703 // Check if we have any device clause associated with the directive.
3704 const Expr *Device = nullptr;
3705 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3706 Device = C->getDevice();
3707
Samuel Antaocc10b852016-07-28 14:23:26 +00003708 // Set the action to signal privatization of device pointers.
3709 RCG.setAction(PrivAction);
3710
3711 // Emit region code.
3712 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3713 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003714}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003715
Samuel Antaodf67fc42016-01-19 19:15:56 +00003716void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3717 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003718 // If we don't have target devices, don't bother emitting the data mapping
3719 // code.
3720 if (CGM.getLangOpts().OMPTargetTriples.empty())
3721 return;
3722
3723 // Check if we have any if clause associated with the directive.
3724 const Expr *IfCond = nullptr;
3725 if (auto *C = S.getSingleClause<OMPIfClause>())
3726 IfCond = C->getCondition();
3727
3728 // Check if we have any device clause associated with the directive.
3729 const Expr *Device = nullptr;
3730 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3731 Device = C->getDevice();
3732
Samuel Antao8d2d7302016-05-26 18:30:22 +00003733 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003734}
3735
Samuel Antao72590762016-01-19 20:04:50 +00003736void CodeGenFunction::EmitOMPTargetExitDataDirective(
3737 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003738 // If we don't have target devices, don't bother emitting the data mapping
3739 // code.
3740 if (CGM.getLangOpts().OMPTargetTriples.empty())
3741 return;
3742
3743 // Check if we have any if clause associated with the directive.
3744 const Expr *IfCond = nullptr;
3745 if (auto *C = S.getSingleClause<OMPIfClause>())
3746 IfCond = C->getCondition();
3747
3748 // Check if we have any device clause associated with the directive.
3749 const Expr *Device = nullptr;
3750 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3751 Device = C->getDevice();
3752
Samuel Antao8d2d7302016-05-26 18:30:22 +00003753 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003754}
3755
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003756static void emitTargetParallelRegion(CodeGenFunction &CGF,
3757 const OMPTargetParallelDirective &S,
3758 PrePostActionTy &Action) {
3759 // Get the captured statement associated with the 'parallel' region.
3760 auto *CS = S.getCapturedStmt(OMPD_parallel);
3761 Action.Enter(CGF);
3762 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3763 // TODO: Add support for clauses.
3764 CGF.EmitStmt(CS->getCapturedStmt());
3765 };
3766 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen);
3767}
3768
3769void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
3770 CodeGenModule &CGM, StringRef ParentName,
3771 const OMPTargetParallelDirective &S) {
3772 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3773 emitTargetParallelRegion(CGF, S, Action);
3774 };
3775 llvm::Function *Fn;
3776 llvm::Constant *Addr;
3777 // Emit target region as a standalone region.
3778 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3779 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3780 assert(Fn && Addr && "Target device function emission failed.");
3781}
3782
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003783void CodeGenFunction::EmitOMPTargetParallelDirective(
3784 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003785 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3786 emitTargetParallelRegion(CGF, S, Action);
3787 };
3788 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003789}
3790
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003791void CodeGenFunction::EmitOMPTargetParallelForDirective(
3792 const OMPTargetParallelForDirective &S) {
3793 // TODO: codegen for target parallel for.
3794}
3795
Alexey Bataev7292c292016-04-25 12:22:29 +00003796/// Emit a helper variable and return corresponding lvalue.
3797static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3798 const ImplicitParamDecl *PVD,
3799 CodeGenFunction::OMPPrivateScope &Privates) {
3800 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3801 Privates.addPrivate(
3802 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3803}
3804
3805void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3806 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3807 // Emit outlined function for task construct.
3808 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3809 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3810 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3811 const Expr *IfCond = nullptr;
3812 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3813 if (C->getNameModifier() == OMPD_unknown ||
3814 C->getNameModifier() == OMPD_taskloop) {
3815 IfCond = C->getCondition();
3816 break;
3817 }
3818 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003819
3820 OMPTaskDataTy Data;
3821 // Check if taskloop must be emitted without taskgroup.
3822 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003823 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003824 Data.Tied = true;
3825 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003826 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3827 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003828 Data.Schedule.setInt(/*IntVal=*/false);
3829 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003830 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3831 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003832 Data.Schedule.setInt(/*IntVal=*/true);
3833 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003834 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003835
3836 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3837 // if (PreCond) {
3838 // for (IV in 0..LastIteration) BODY;
3839 // <Final counter/linear vars updates>;
3840 // }
3841 //
3842
3843 // Emit: if (PreCond) - begin.
3844 // If the condition constant folds and can be elided, avoid emitting the
3845 // whole loop.
3846 bool CondConstant;
3847 llvm::BasicBlock *ContBlock = nullptr;
3848 OMPLoopScope PreInitScope(CGF, S);
3849 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3850 if (!CondConstant)
3851 return;
3852 } else {
3853 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3854 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3855 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3856 CGF.getProfileCount(&S));
3857 CGF.EmitBlock(ThenBlock);
3858 CGF.incrementProfileCounter(&S);
3859 }
3860
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003861 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3862 CGF.EmitOMPSimdInit(S);
3863
Alexey Bataev7292c292016-04-25 12:22:29 +00003864 OMPPrivateScope LoopScope(CGF);
3865 // Emit helper vars inits.
3866 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3867 auto *I = CS->getCapturedDecl()->param_begin();
3868 auto *LBP = std::next(I, LowerBound);
3869 auto *UBP = std::next(I, UpperBound);
3870 auto *STP = std::next(I, Stride);
3871 auto *LIP = std::next(I, LastIter);
3872 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3873 LoopScope);
3874 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3875 LoopScope);
3876 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3877 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3878 LoopScope);
3879 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003880 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003881 (void)LoopScope.Privatize();
3882 // Emit the loop iteration variable.
3883 const Expr *IVExpr = S.getIterationVariable();
3884 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3885 CGF.EmitVarDecl(*IVDecl);
3886 CGF.EmitIgnoredExpr(S.getInit());
3887
3888 // Emit the iterations count variable.
3889 // If it is not a variable, Sema decided to calculate iterations count on
3890 // each iteration (e.g., it is foldable into a constant).
3891 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3892 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3893 // Emit calculation of the iterations count.
3894 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3895 }
3896
3897 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3898 S.getInc(),
3899 [&S](CodeGenFunction &CGF) {
3900 CGF.EmitOMPLoopBody(S, JumpDest());
3901 CGF.EmitStopPoint(&S);
3902 },
3903 [](CodeGenFunction &) {});
3904 // Emit: if (PreCond) - end.
3905 if (ContBlock) {
3906 CGF.EmitBranch(ContBlock);
3907 CGF.EmitBlock(ContBlock, true);
3908 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003909 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3910 if (HasLastprivateClause) {
3911 CGF.EmitOMPLastprivateClauseFinal(
3912 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3913 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3914 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3915 (*LIP)->getType(), S.getLocStart())));
3916 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003917 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003918 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3919 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3920 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003921 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3922 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003923 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
3924 OutlinedFn, SharedsTy,
3925 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003926 };
3927 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
3928 CodeGen);
3929 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003930 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003931}
3932
Alexey Bataev49f6e782015-12-01 04:18:41 +00003933void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003934 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003935}
3936
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003937void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3938 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003939 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003940}
Samuel Antao686c70c2016-05-26 17:30:50 +00003941
3942// Generate the instructions for '#pragma omp target update' directive.
3943void CodeGenFunction::EmitOMPTargetUpdateDirective(
3944 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00003945 // If we don't have target devices, don't bother emitting the data mapping
3946 // code.
3947 if (CGM.getLangOpts().OMPTargetTriples.empty())
3948 return;
3949
3950 // Check if we have any if clause associated with the directive.
3951 const Expr *IfCond = nullptr;
3952 if (auto *C = S.getSingleClause<OMPIfClause>())
3953 IfCond = C->getCondition();
3954
3955 // Check if we have any device clause associated with the directive.
3956 const Expr *Device = nullptr;
3957 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3958 Device = C->getDevice();
3959
3960 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00003961}