blob: c4f8311f2ea9604912c4ccf387eab95ec8db6d7c [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 Bataev14fa1c62016-03-29 05:34:15 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev14fa1c62016-03-29 05:34:15 +000050 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()) {
Alexey Bataev3392d762016-02-16 11:18:12 +000051 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000054
Alexey Bataev5a3af132016-03-29 08:58:54 +000055/// Private scope for OpenMP loop-based directives, that supports capturing
56/// of used expression from loop statement.
57class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
58 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
59 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
60 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
61 for (const auto *I : PreInits->decls())
62 CGF.EmitVarDecl(cast<VarDecl>(*I));
63 }
64 }
65 }
66
67public:
68 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
69 : CodeGenFunction::RunCleanupsScope(CGF) {
70 emitPreInitStmt(CGF, S);
71 }
72};
73
Alexey Bataev3392d762016-02-16 11:18:12 +000074} // namespace
75
Alexey Bataev1189bd02016-01-26 12:20:39 +000076llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
77 auto &C = getContext();
78 llvm::Value *Size = nullptr;
79 auto SizeInChars = C.getTypeSizeInChars(Ty);
80 if (SizeInChars.isZero()) {
81 // getTypeSizeInChars() returns 0 for a VLA.
82 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
83 llvm::Value *ArraySize;
84 std::tie(ArraySize, Ty) = getVLASize(VAT);
85 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
86 }
87 SizeInChars = C.getTypeSizeInChars(Ty);
88 if (SizeInChars.isZero())
89 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
90 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
91 } else
92 Size = CGM.getSize(SizeInChars);
93 return Size;
94}
95
Alexey Bataev2377fe92015-09-10 08:12:02 +000096void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000098 const RecordDecl *RD = S.getCapturedRecordDecl();
99 auto CurField = RD->field_begin();
100 auto CurCap = S.captures().begin();
101 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
102 E = S.capture_init_end();
103 I != E; ++I, ++CurField, ++CurCap) {
104 if (CurField->hasCapturedVLAType()) {
105 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000106 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000107 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000108 } else if (CurCap->capturesThis())
109 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000110 else if (CurCap->capturesVariableByCopy())
111 CapturedVars.push_back(
112 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
113 else {
114 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000115 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000116 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000117 }
118}
119
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000120static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
121 StringRef Name, LValue AddrLV,
122 bool isReferenceType = false) {
123 ASTContext &Ctx = CGF.getContext();
124
125 auto *CastedPtr = CGF.EmitScalarConversion(
126 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
127 Ctx.getPointerType(DstType), SourceLocation());
128 auto TmpAddr =
129 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
130 .getAddress();
131
132 // If we are dealing with references we need to return the address of the
133 // reference instead of the reference of the value.
134 if (isReferenceType) {
135 QualType RefType = Ctx.getLValueReferenceType(DstType);
136 auto *RefVal = TmpAddr.getPointer();
137 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
138 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
139 CGF.EmitScalarInit(RefVal, TmpLVal);
140 }
141
142 return TmpAddr;
143}
144
Alexey Bataev2377fe92015-09-10 08:12:02 +0000145llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000146CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000147 assert(
148 CapturedStmtInfo &&
149 "CapturedStmtInfo should be set when generating the captured function");
150 const CapturedDecl *CD = S.getCapturedDecl();
151 const RecordDecl *RD = S.getCapturedRecordDecl();
152 assert(CD->hasBody() && "missing CapturedDecl body");
153
154 // Build the argument list.
155 ASTContext &Ctx = CGM.getContext();
156 FunctionArgList Args;
157 Args.append(CD->param_begin(),
158 std::next(CD->param_begin(), CD->getContextParamPosition()));
159 auto I = S.captures().begin();
160 for (auto *FD : RD->fields()) {
161 QualType ArgType = FD->getType();
162 IdentifierInfo *II = nullptr;
163 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000164
165 // If this is a capture by copy and the type is not a pointer, the outlined
166 // function argument type should be uintptr and the value properly casted to
167 // uintptr. This is necessary given that the runtime library is only able to
168 // deal with pointers. We can pass in the same way the VLA type sizes to the
169 // outlined function.
170 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
171 I->capturesVariableArrayType())
172 ArgType = Ctx.getUIntPtrType();
173
174 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000175 CapVar = I->getCapturedVar();
176 II = CapVar->getIdentifier();
177 } else if (I->capturesThis())
178 II = &getContext().Idents.get("this");
179 else {
180 assert(I->capturesVariableArrayType());
181 II = &getContext().Idents.get("vla");
182 }
183 if (ArgType->isVariablyModifiedType())
184 ArgType = getContext().getVariableArrayDecayedType(ArgType);
185 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
186 FD->getLocation(), II, ArgType));
187 ++I;
188 }
189 Args.append(
190 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
191 CD->param_end());
192
193 // Create the function declaration.
194 FunctionType::ExtInfo ExtInfo;
195 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000196 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000197 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
198
199 llvm::Function *F = llvm::Function::Create(
200 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
201 CapturedStmtInfo->getHelperName(), &CGM.getModule());
202 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
203 if (CD->isNothrow())
204 F->addFnAttr(llvm::Attribute::NoUnwind);
205
206 // Generate the function.
207 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
208 CD->getBody()->getLocStart());
209 unsigned Cnt = CD->getContextParamPosition();
210 I = S.captures().begin();
211 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000212 // If we are capturing a pointer by copy we don't need to do anything, just
213 // use the value that we get from the arguments.
214 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
215 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000216 ++Cnt;
217 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000218 continue;
219 }
220
Alexey Bataev2377fe92015-09-10 08:12:02 +0000221 LValue ArgLVal =
222 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
223 AlignmentSource::Decl);
224 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225 LValue CastedArgLVal =
226 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
227 Args[Cnt]->getName(), ArgLVal),
228 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000229 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000231 auto VAT = FD->getCapturedVLAType();
232 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
233 } else if (I->capturesVariable()) {
234 auto *Var = I->getCapturedVar();
235 QualType VarTy = Var->getType();
236 Address ArgAddr = ArgLVal.getAddress();
237 if (!VarTy->isReferenceType()) {
238 ArgAddr = EmitLoadOfReference(
239 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
240 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000241 setAddrOfLocalVar(
242 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000243 } else if (I->capturesVariableByCopy()) {
244 assert(!FD->getType()->isAnyPointerType() &&
245 "Not expecting a captured pointer.");
246 auto *Var = I->getCapturedVar();
247 QualType VarTy = Var->getType();
248 setAddrOfLocalVar(I->getCapturedVar(),
249 castValueFromUintptr(*this, FD->getType(),
250 Args[Cnt]->getName(), ArgLVal,
251 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000252 } else {
253 // If 'this' is captured, load it into CXXThisValue.
254 assert(I->capturesThis());
255 CXXThisValue =
256 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
257 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000258 ++Cnt;
259 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000260 }
261
Serge Pavlov3a561452015-12-06 14:32:39 +0000262 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000263 CapturedStmtInfo->EmitBody(*this, CD->getBody());
264 FinishFunction(CD->getBodyRBrace());
265
266 return F;
267}
268
Alexey Bataev9959db52014-05-06 10:08:46 +0000269//===----------------------------------------------------------------------===//
270// OpenMP Directive Emission
271//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000272void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address DestAddr, Address SrcAddr, QualType OriginalType,
274 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Perform element-by-element initialization.
276 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000277
278 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000279 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000280 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
281 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
282
283 auto SrcBegin = SrcAddr.getPointer();
284 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000285 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000286 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
287 // The basic structure here is a while-do loop.
288 auto BodyBB = createBasicBlock("omp.arraycpy.body");
289 auto DoneBB = createBasicBlock("omp.arraycpy.done");
290 auto IsEmpty =
291 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
292 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000293
Alexey Bataev420d45b2015-04-14 05:11:24 +0000294 // Enter the loop body, making that address the current address.
295 auto EntryBB = Builder.GetInsertBlock();
296 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000297
298 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
299
300 llvm::PHINode *SrcElementPHI =
301 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
302 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
303 Address SrcElementCurrent =
304 Address(SrcElementPHI,
305 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
306
307 llvm::PHINode *DestElementPHI =
308 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
309 DestElementPHI->addIncoming(DestBegin, EntryBB);
310 Address DestElementCurrent =
311 Address(DestElementPHI,
312 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000313
Alexey Bataev420d45b2015-04-14 05:11:24 +0000314 // Emit copy.
315 CopyGen(DestElementCurrent, SrcElementCurrent);
316
317 // Shift the address forward by one element.
318 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000319 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000320 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000321 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000322 // Check whether we've reached the end.
323 auto Done =
324 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
325 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000326 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
327 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000328
329 // Done.
330 EmitBlock(DoneBB, /*IsFinished=*/true);
331}
332
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000333/// Check if the combiner is a call to UDR combiner and if it is so return the
334/// UDR decl used for reduction.
335static const OMPDeclareReductionDecl *
336getReductionInit(const Expr *ReductionOp) {
337 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
338 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
339 if (auto *DRE =
340 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
341 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
342 return DRD;
343 return nullptr;
344}
345
346static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
347 const OMPDeclareReductionDecl *DRD,
348 const Expr *InitOp,
349 Address Private, Address Original,
350 QualType Ty) {
351 if (DRD->getInitializer()) {
352 std::pair<llvm::Function *, llvm::Function *> Reduction =
353 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
354 auto *CE = cast<CallExpr>(InitOp);
355 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
356 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
357 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
358 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
359 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
360 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
361 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
362 [=]() -> Address { return Private; });
363 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
364 [=]() -> Address { return Original; });
365 (void)PrivateScope.Privatize();
366 RValue Func = RValue::get(Reduction.second);
367 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
368 CGF.EmitIgnoredExpr(InitOp);
369 } else {
370 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
371 auto *GV = new llvm::GlobalVariable(
372 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
373 llvm::GlobalValue::PrivateLinkage, Init, ".init");
374 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
375 RValue InitRVal;
376 switch (CGF.getEvaluationKind(Ty)) {
377 case TEK_Scalar:
378 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
379 break;
380 case TEK_Complex:
381 InitRVal =
382 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
383 break;
384 case TEK_Aggregate:
385 InitRVal = RValue::getAggregate(LV.getAddress());
386 break;
387 }
388 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
389 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
390 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
391 /*IsInitializer=*/false);
392 }
393}
394
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000395/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000396/// \param DestAddr Address of the array.
397/// \param Type Type of array.
398/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000399/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000400static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000401 QualType Type, const Expr *Init,
402 Address SrcAddr = Address::invalid()) {
403 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000404 // Perform element-by-element initialization.
405 QualType ElementTy;
406
407 // Drill down to the base element type on both arrays.
408 auto ArrayTy = Type->getAsArrayTypeUnsafe();
409 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
410 DestAddr =
411 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000412 if (DRD)
413 SrcAddr =
414 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000415
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000416 llvm::Value *SrcBegin = nullptr;
417 if (DRD)
418 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000419 auto DestBegin = DestAddr.getPointer();
420 // Cast from pointer to array type to pointer to single element.
421 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
422 // The basic structure here is a while-do loop.
423 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
424 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
425 auto IsEmpty =
426 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
427 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
428
429 // Enter the loop body, making that address the current address.
430 auto EntryBB = CGF.Builder.GetInsertBlock();
431 CGF.EmitBlock(BodyBB);
432
433 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
434
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000435 llvm::PHINode *SrcElementPHI = nullptr;
436 Address SrcElementCurrent = Address::invalid();
437 if (DRD) {
438 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
439 "omp.arraycpy.srcElementPast");
440 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
441 SrcElementCurrent =
442 Address(SrcElementPHI,
443 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
444 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000445 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
446 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
447 DestElementPHI->addIncoming(DestBegin, EntryBB);
448 Address DestElementCurrent =
449 Address(DestElementPHI,
450 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
451
452 // Emit copy.
453 {
454 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000455 if (DRD) {
456 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
457 SrcElementCurrent, ElementTy);
458 } else
459 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
460 /*IsInitializer=*/false);
461 }
462
463 if (DRD) {
464 // Shift the address forward by one element.
465 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
466 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
467 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000468 }
469
470 // Shift the address forward by one element.
471 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
472 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
473 // Check whether we've reached the end.
474 auto Done =
475 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
476 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
477 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
478
479 // Done.
480 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
481}
482
John McCall7f416cc2015-09-08 08:05:57 +0000483void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
484 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000485 const VarDecl *SrcVD, const Expr *Copy) {
486 if (OriginalType->isArrayType()) {
487 auto *BO = dyn_cast<BinaryOperator>(Copy);
488 if (BO && BO->getOpcode() == BO_Assign) {
489 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000490 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000491 } else {
492 // For arrays with complex element types perform element by element
493 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000494 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000495 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000496 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000497 // Working with the single array element, so have to remap
498 // destination and source variables to corresponding array
499 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000500 CodeGenFunction::OMPPrivateScope Remap(*this);
501 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000502 return DestElement;
503 });
504 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000505 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000506 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000507 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000508 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000509 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000510 } else {
511 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000512 CodeGenFunction::OMPPrivateScope Remap(*this);
513 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
514 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000515 (void)Remap.Privatize();
516 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000517 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000518 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000519}
520
Alexey Bataev69c62a92015-04-15 04:52:20 +0000521bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
522 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000523 if (!HaveInsertPoint())
524 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000525 bool FirstprivateIsLastprivate = false;
526 llvm::DenseSet<const VarDecl *> Lastprivates;
527 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
528 for (const auto *D : C->varlists())
529 Lastprivates.insert(
530 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
531 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000532 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000533 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000534 auto IRef = C->varlist_begin();
535 auto InitsRef = C->inits().begin();
536 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000537 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000538 FirstprivateIsLastprivate =
539 FirstprivateIsLastprivate ||
540 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
541 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000542 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
543 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
544 bool IsRegistered;
545 DeclRefExpr DRE(
546 const_cast<VarDecl *>(OrigVD),
547 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
548 OrigVD) != nullptr,
549 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000550 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000551 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000552 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000553 // Emit VarDecl with copy init for arrays.
554 // Get the address of the original variable captured in current
555 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000556 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000557 auto Emission = EmitAutoVarAlloca(*VD);
558 auto *Init = VD->getInit();
559 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
560 // Perform simple memcpy.
561 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000562 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000563 } else {
564 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000565 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000566 [this, VDInit, Init](Address DestElement,
567 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000568 // Clean up any temporaries needed by the initialization.
569 RunCleanupsScope InitScope(*this);
570 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000571 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000572 EmitAnyExprToMem(Init, DestElement,
573 Init->getType().getQualifiers(),
574 /*IsInitializer*/ false);
575 LocalDeclMap.erase(VDInit);
576 });
577 }
578 EmitAutoVarCleanups(Emission);
579 return Emission.getAllocatedAddress();
580 });
581 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000582 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000583 // Emit private VarDecl with copy init.
584 // Remap temp VDInit variable to the address of the original
585 // variable
586 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000587 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000588 EmitDecl(*VD);
589 LocalDeclMap.erase(VDInit);
590 return GetAddrOfLocalVar(VD);
591 });
592 }
593 assert(IsRegistered &&
594 "firstprivate var already registered as private");
595 // Silence the warning about unused variable.
596 (void)IsRegistered;
597 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000598 ++IRef;
599 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000600 }
601 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000602 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000603}
604
Alexey Bataev03b340a2014-10-21 03:16:40 +0000605void CodeGenFunction::EmitOMPPrivateClause(
606 const OMPExecutableDirective &D,
607 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000608 if (!HaveInsertPoint())
609 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000610 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000611 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000612 auto IRef = C->varlist_begin();
613 for (auto IInit : C->private_copies()) {
614 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000615 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
616 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
617 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000618 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000619 // Emit private VarDecl with copy init.
620 EmitDecl(*VD);
621 return GetAddrOfLocalVar(VD);
622 });
623 assert(IsRegistered && "private var already registered as private");
624 // Silence the warning about unused variable.
625 (void)IsRegistered;
626 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000627 ++IRef;
628 }
629 }
630}
631
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000632bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000633 if (!HaveInsertPoint())
634 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000635 // threadprivate_var1 = master_threadprivate_var1;
636 // operator=(threadprivate_var2, master_threadprivate_var2);
637 // ...
638 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000639 llvm::DenseSet<const VarDecl *> CopiedVars;
640 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000641 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000642 auto IRef = C->varlist_begin();
643 auto ISrcRef = C->source_exprs().begin();
644 auto IDestRef = C->destination_exprs().begin();
645 for (auto *AssignOp : C->assignment_ops()) {
646 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000647 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000648 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000649 // Get the address of the master variable. If we are emitting code with
650 // TLS support, the address is passed from the master as field in the
651 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000652 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000653 if (getLangOpts().OpenMPUseTLS &&
654 getContext().getTargetInfo().isTLSSupported()) {
655 assert(CapturedStmtInfo->lookup(VD) &&
656 "Copyin threadprivates should have been captured!");
657 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
658 VK_LValue, (*IRef)->getExprLoc());
659 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000660 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000661 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000662 MasterAddr =
663 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
664 : CGM.GetAddrOfGlobal(VD),
665 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000666 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000667 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000668 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000669 if (CopiedVars.size() == 1) {
670 // At first check if current thread is a master thread. If it is, no
671 // need to copy data.
672 CopyBegin = createBasicBlock("copyin.not.master");
673 CopyEnd = createBasicBlock("copyin.not.master.end");
674 Builder.CreateCondBr(
675 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000676 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
677 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000678 CopyBegin, CopyEnd);
679 EmitBlock(CopyBegin);
680 }
681 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
682 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000683 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000684 }
685 ++IRef;
686 ++ISrcRef;
687 ++IDestRef;
688 }
689 }
690 if (CopyEnd) {
691 // Exit out of copying procedure for non-master thread.
692 EmitBlock(CopyEnd, /*IsFinished=*/true);
693 return true;
694 }
695 return false;
696}
697
Alexey Bataev38e89532015-04-16 04:54:05 +0000698bool CodeGenFunction::EmitOMPLastprivateClauseInit(
699 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000700 if (!HaveInsertPoint())
701 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000702 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000703 llvm::DenseSet<const VarDecl *> SIMDLCVs;
704 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
705 auto *LoopDirective = cast<OMPLoopDirective>(&D);
706 for (auto *C : LoopDirective->counters()) {
707 SIMDLCVs.insert(
708 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
709 }
710 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000711 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000712 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000713 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000714 auto IRef = C->varlist_begin();
715 auto IDestRef = C->destination_exprs().begin();
716 for (auto *IInit : C->private_copies()) {
717 // Keep the address of the original variable for future update at the end
718 // of the loop.
719 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
720 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
721 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000722 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000723 DeclRefExpr DRE(
724 const_cast<VarDecl *>(OrigVD),
725 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
726 OrigVD) != nullptr,
727 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
728 return EmitLValue(&DRE).getAddress();
729 });
730 // Check if the variable is also a firstprivate: in this case IInit is
731 // not generated. Initialization of this variable will happen in codegen
732 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000733 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000734 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
735 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000736 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000737 // Emit private VarDecl with copy init.
738 EmitDecl(*VD);
739 return GetAddrOfLocalVar(VD);
740 });
741 assert(IsRegistered &&
742 "lastprivate var already registered as private");
743 (void)IsRegistered;
744 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000745 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000746 ++IRef;
747 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000748 }
749 }
750 return HasAtLeastOneLastprivate;
751}
752
753void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000754 const OMPExecutableDirective &D, bool NoFinals,
755 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000756 if (!HaveInsertPoint())
757 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000758 // Emit following code:
759 // if (<IsLastIterCond>) {
760 // orig_var1 = private_orig_var1;
761 // ...
762 // orig_varn = private_orig_varn;
763 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000764 llvm::BasicBlock *ThenBB = nullptr;
765 llvm::BasicBlock *DoneBB = nullptr;
766 if (IsLastIterCond) {
767 ThenBB = createBasicBlock(".omp.lastprivate.then");
768 DoneBB = createBasicBlock(".omp.lastprivate.done");
769 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
770 EmitBlock(ThenBB);
771 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000772 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
773 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000774 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000775 auto IC = LoopDirective->counters().begin();
776 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000777 auto *D =
778 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
779 if (NoFinals)
780 AlreadyEmittedVars.insert(D);
781 else
782 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000783 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000784 }
785 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000786 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
787 auto IRef = C->varlist_begin();
788 auto ISrcRef = C->source_exprs().begin();
789 auto IDestRef = C->destination_exprs().begin();
790 for (auto *AssignOp : C->assignment_ops()) {
791 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
792 QualType Type = PrivateVD->getType();
793 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
794 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
795 // If lastprivate variable is a loop control variable for loop-based
796 // directive, update its value before copyin back to original
797 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000798 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
799 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000800 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
801 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
802 // Get the address of the original variable.
803 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
804 // Get the address of the private variable.
805 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
806 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
807 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000808 Address(Builder.CreateLoad(PrivateAddr),
809 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000810 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000811 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000812 ++IRef;
813 ++ISrcRef;
814 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000815 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000816 if (auto *PostUpdate = C->getPostUpdateExpr())
817 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000818 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000819 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000820 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000821}
822
Alexey Bataev31300ed2016-02-04 11:27:03 +0000823static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
824 LValue BaseLV, llvm::Value *Addr) {
825 Address Tmp = Address::invalid();
826 Address TopTmp = Address::invalid();
827 Address MostTopTmp = Address::invalid();
828 BaseTy = BaseTy.getNonReferenceType();
829 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
830 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
831 Tmp = CGF.CreateMemTemp(BaseTy);
832 if (TopTmp.isValid())
833 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
834 else
835 MostTopTmp = Tmp;
836 TopTmp = Tmp;
837 BaseTy = BaseTy->getPointeeType();
838 }
839 llvm::Type *Ty = BaseLV.getPointer()->getType();
840 if (Tmp.isValid())
841 Ty = Tmp.getElementType();
842 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
843 if (Tmp.isValid()) {
844 CGF.Builder.CreateStore(Addr, Tmp);
845 return MostTopTmp;
846 }
847 return Address(Addr, BaseLV.getAlignment());
848}
849
850static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
851 LValue BaseLV) {
852 BaseTy = BaseTy.getNonReferenceType();
853 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
854 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
855 if (auto *PtrTy = BaseTy->getAs<PointerType>())
856 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
857 else {
858 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
859 BaseTy->castAs<ReferenceType>());
860 }
861 BaseTy = BaseTy->getPointeeType();
862 }
863 return CGF.MakeAddrLValue(
864 Address(
865 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
866 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
867 BaseLV.getAlignment()),
868 BaseLV.getType(), BaseLV.getAlignmentSource());
869}
870
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000871void CodeGenFunction::EmitOMPReductionClauseInit(
872 const OMPExecutableDirective &D,
873 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000874 if (!HaveInsertPoint())
875 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000876 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000877 auto ILHS = C->lhs_exprs().begin();
878 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000879 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000880 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000881 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000882 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000883 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
884 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000885 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000886 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
887 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
888 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
889 Base = TempOASE->getBase()->IgnoreParenImpCasts();
890 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
891 Base = TempASE->getBase()->IgnoreParenImpCasts();
892 auto *DE = cast<DeclRefExpr>(Base);
893 auto *OrigVD = cast<VarDecl>(DE->getDecl());
894 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
895 auto OASELValueUB =
896 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
897 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000898 LValue BaseLValue =
899 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
900 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000901 // Store the address of the original variable associated with the LHS
902 // implicit variable.
903 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
904 return OASELValueLB.getAddress();
905 });
906 // Emit reduction copy.
907 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000908 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000909 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000910 // Emit VarDecl with copy init for arrays.
911 // Get the address of the original variable captured in current
912 // captured region.
913 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
914 OASELValueLB.getPointer());
915 Size = Builder.CreateNUWAdd(
916 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
917 CodeGenFunction::OpaqueValueMapping OpaqueMap(
918 *this, cast<OpaqueValueExpr>(
919 getContext()
920 .getAsVariableArrayType(PrivateVD->getType())
921 ->getSizeExpr()),
922 RValue::get(Size));
923 EmitVariablyModifiedType(PrivateVD->getType());
924 auto Emission = EmitAutoVarAlloca(*PrivateVD);
925 auto Addr = Emission.getAllocatedAddress();
926 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000927 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
928 DRD ? *IRed : Init,
929 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 EmitAutoVarCleanups(Emission);
931 // Emit private VarDecl with reduction init.
932 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
933 OASELValueLB.getPointer());
934 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000935 return castToBase(*this, OrigVD->getType(),
936 OASELValueLB.getType(), OriginalBaseLValue,
937 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000938 });
939 assert(IsRegistered && "private var already registered as private");
940 // Silence the warning about unused variable.
941 (void)IsRegistered;
942 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
943 return GetAddrOfLocalVar(PrivateVD);
944 });
945 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
946 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
947 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
948 Base = TempASE->getBase()->IgnoreParenImpCasts();
949 auto *DE = cast<DeclRefExpr>(Base);
950 auto *OrigVD = cast<VarDecl>(DE->getDecl());
951 auto ASELValue = EmitLValue(ASE);
952 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000953 LValue BaseLValue = loadToBegin(
954 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000955 // Store the address of the original variable associated with the LHS
956 // implicit variable.
957 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
958 return ASELValue.getAddress();
959 });
960 // Emit reduction copy.
961 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000962 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000963 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000964 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000965 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
966 auto Addr = Emission.getAllocatedAddress();
967 if (DRD) {
968 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
969 ASELValue.getAddress(),
970 ASELValue.getType());
971 } else
972 EmitAutoVarInit(Emission);
973 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000974 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
975 ASELValue.getPointer());
976 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000977 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
978 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000979 });
980 assert(IsRegistered && "private var already registered as private");
981 // Silence the warning about unused variable.
982 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000983 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
984 return Builder.CreateElementBitCast(
985 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
986 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000987 });
988 } else {
989 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000990 QualType Type = PrivateVD->getType();
991 if (getContext().getAsArrayType(Type)) {
992 // Store the address of the original variable associated with the LHS
993 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000994 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
995 CapturedStmtInfo->lookup(OrigVD) != nullptr,
996 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000997 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000998 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +0000999 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001000 OriginalAddr = Builder.CreateElementBitCast(
1001 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1002 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001003 });
1004 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1005 if (Type->isVariablyModifiedType()) {
1006 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1007 *this, cast<OpaqueValueExpr>(
1008 getContext()
1009 .getAsVariableArrayType(PrivateVD->getType())
1010 ->getSizeExpr()),
1011 RValue::get(
1012 getTypeSize(OrigVD->getType().getNonReferenceType())));
1013 EmitVariablyModifiedType(Type);
1014 }
1015 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1016 auto Addr = Emission.getAllocatedAddress();
1017 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001018 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1019 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001020 EmitAutoVarCleanups(Emission);
1021 return Emission.getAllocatedAddress();
1022 });
1023 assert(IsRegistered && "private var already registered as private");
1024 // Silence the warning about unused variable.
1025 (void)IsRegistered;
1026 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1027 return Builder.CreateElementBitCast(
1028 GetAddrOfLocalVar(PrivateVD),
1029 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1030 });
1031 } else {
1032 // Store the address of the original variable associated with the LHS
1033 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001034 Address OriginalAddr = Address::invalid();
1035 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1036 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001037 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1038 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1039 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001040 OriginalAddr = EmitLValue(&DRE).getAddress();
1041 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001042 });
1043 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001044 bool IsRegistered = PrivateScope.addPrivate(
1045 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001046 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001047 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1048 auto Addr = Emission.getAllocatedAddress();
1049 if (DRD) {
1050 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1051 OriginalAddr,
1052 PrivateVD->getType());
1053 } else
1054 EmitAutoVarInit(Emission);
1055 EmitAutoVarCleanups(Emission);
1056 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001057 });
1058 assert(IsRegistered && "private var already registered as private");
1059 // Silence the warning about unused variable.
1060 (void)IsRegistered;
1061 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1062 return GetAddrOfLocalVar(PrivateVD);
1063 });
1064 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001065 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001066 ++ILHS;
1067 ++IRHS;
1068 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001069 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001070 }
1071 }
1072}
1073
1074void CodeGenFunction::EmitOMPReductionClauseFinal(
1075 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001076 if (!HaveInsertPoint())
1077 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001078 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001079 llvm::SmallVector<const Expr *, 8> LHSExprs;
1080 llvm::SmallVector<const Expr *, 8> RHSExprs;
1081 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001082 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001083 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001084 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001085 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001086 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1087 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1088 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1089 }
1090 if (HasAtLeastOneReduction) {
1091 // Emit nowait reduction if nowait clause is present or directive is a
1092 // parallel directive (it always has implicit barrier).
1093 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001094 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001095 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001096 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1097 D.getDirectiveKind() == OMPD_simd,
1098 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001099 }
1100}
1101
Alexey Bataev61205072016-03-02 04:57:40 +00001102static void emitPostUpdateForReductionClause(
1103 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1104 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1105 if (!CGF.HaveInsertPoint())
1106 return;
1107 llvm::BasicBlock *DoneBB = nullptr;
1108 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1109 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1110 if (!DoneBB) {
1111 if (auto *Cond = CondGen(CGF)) {
1112 // If the first post-update expression is found, emit conditional
1113 // block if it was requested.
1114 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1115 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1116 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1117 CGF.EmitBlock(ThenBB);
1118 }
1119 }
1120 CGF.EmitIgnoredExpr(PostUpdate);
1121 }
1122 }
1123 if (DoneBB)
1124 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1125}
1126
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001127static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1128 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001129 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001131 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001132 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1133 emitParallelOrTeamsOutlinedFunction(S,
1134 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001135 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001136 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001137 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1138 /*IgnoreResultAssign*/ true);
1139 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1140 CGF, NumThreads, NumThreadsClause->getLocStart());
1141 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001142 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001143 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001144 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1145 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1146 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001147 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001148 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1149 if (C->getNameModifier() == OMPD_unknown ||
1150 C->getNameModifier() == OMPD_parallel) {
1151 IfCond = C->getCondition();
1152 break;
1153 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001154 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001155
1156 OMPLexicalScope Scope(CGF, S);
1157 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1158 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001159 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001160 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001161}
1162
1163void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001164 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001166 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001167 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001168 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1169 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001170 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001171 // propagation master's thread values of threadprivate variables to local
1172 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001173 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1174 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1175 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001176 }
1177 CGF.EmitOMPPrivateClause(S, PrivateScope);
1178 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1179 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001181 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001183 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001184 emitPostUpdateForReductionClause(
1185 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001186}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001187
Alexey Bataev0f34da12015-07-02 04:17:07 +00001188void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1189 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001190 RunCleanupsScope BodyScope(*this);
1191 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001192 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001193 EmitIgnoredExpr(I);
1194 }
Alexander Musman3276a272015-03-21 10:12:56 +00001195 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001196 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001197 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001198 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001199 }
1200
Alexander Musmana5f070a2014-10-01 06:03:56 +00001201 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001202 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001203 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001204 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001205 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001206 // The end (updates/cleanups).
1207 EmitBlock(Continue.getBlock());
1208 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001209}
1210
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001211void CodeGenFunction::EmitOMPInnerLoop(
1212 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1213 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001214 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1215 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001216 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001217
1218 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001219 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001220 EmitBlock(CondBlock);
1221 LoopStack.push(CondBlock);
1222
1223 // If there are any cleanups between here and the loop-exit scope,
1224 // create a block to stage a loop exit along.
1225 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001226 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001227 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001228
Alexander Musmand196ef22014-10-07 08:57:09 +00001229 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001230
Alexey Bataev2df54a02015-03-12 08:53:29 +00001231 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001232 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001233 if (ExitBlock != LoopExit.getBlock()) {
1234 EmitBlock(ExitBlock);
1235 EmitBranchThroughCleanup(LoopExit);
1236 }
1237
1238 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001239 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001240
1241 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001242 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001243 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1244
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246
1247 // Emit "IV = IV + 1" and a back-edge to the condition block.
1248 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001249 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001250 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001251 BreakContinueStack.pop_back();
1252 EmitBranch(CondBlock);
1253 LoopStack.pop();
1254 // Emit the fall-through block.
1255 EmitBlock(LoopExit.getBlock());
1256}
1257
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001258void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001259 if (!HaveInsertPoint())
1260 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001261 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001262 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001263 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001264 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001265 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1266 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1267 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1268 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1269 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1270 VD->getInit()->getType(), VK_LValue,
1271 VD->getInit()->getExprLoc());
1272 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1273 VD->getType()),
1274 /*capturedByInit=*/false);
1275 EmitAutoVarCleanups(Emission);
1276 } else
1277 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001278 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001279 // Emit the linear steps for the linear clauses.
1280 // If a step is not constant, it is pre-calculated before the loop.
1281 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1282 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001283 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001284 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001285 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001286 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001287 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001288}
1289
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001290void CodeGenFunction::EmitOMPLinearClauseFinal(
1291 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001292 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001293 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001294 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001295 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001296 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001297 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001298 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001299 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001300 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001301 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001302 // If the first post-update expression is found, emit conditional
1303 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001304 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1305 DoneBB = createBasicBlock(".omp.linear.pu.done");
1306 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1307 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001308 }
1309 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001310 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1311 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001312 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001313 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001314 Address OrigAddr = EmitLValue(&DRE).getAddress();
1315 CodeGenFunction::OMPPrivateScope VarScope(*this);
1316 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001317 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001318 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001319 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001320 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001321 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001322 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001323 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001324 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001325 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326}
1327
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001328static void emitAlignedClause(CodeGenFunction &CGF,
1329 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001330 if (!CGF.HaveInsertPoint())
1331 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001332 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001333 unsigned ClauseAlignment = 0;
1334 if (auto AlignmentExpr = Clause->getAlignment()) {
1335 auto AlignmentCI =
1336 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1337 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001338 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001339 for (auto E : Clause->varlists()) {
1340 unsigned Alignment = ClauseAlignment;
1341 if (Alignment == 0) {
1342 // OpenMP [2.8.1, Description]
1343 // If no optional parameter is specified, implementation-defined default
1344 // alignments for SIMD instructions on the target platforms are assumed.
1345 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001346 CGF.getContext()
1347 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1348 E->getType()->getPointeeType()))
1349 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001350 }
1351 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1352 "alignment is not power of 2");
1353 if (Alignment != 0) {
1354 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1355 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1356 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001357 }
1358 }
1359}
1360
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001361void CodeGenFunction::EmitOMPPrivateLoopCounters(
1362 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1363 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001364 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001365 auto I = S.private_counters().begin();
1366 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001367 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1368 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001369 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001370 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001371 if (!LocalDeclMap.count(PrivateVD)) {
1372 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1373 EmitAutoVarCleanups(VarEmission);
1374 }
1375 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1376 /*RefersToEnclosingVariableOrCapture=*/false,
1377 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1378 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001379 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001380 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1381 VD->hasGlobalStorage()) {
1382 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1383 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1384 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1385 E->getType(), VK_LValue, E->getExprLoc());
1386 return EmitLValue(&DRE).getAddress();
1387 });
1388 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001389 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001390 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001391}
1392
Alexey Bataev62dbb972015-04-22 11:59:37 +00001393static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1394 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1395 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001396 if (!CGF.HaveInsertPoint())
1397 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001398 {
1399 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001401 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001402 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001403 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001404 CGF.EmitIgnoredExpr(I);
1405 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001406 }
1407 // Check that loop is executed at least one time.
1408 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1409}
1410
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411void CodeGenFunction::EmitOMPLinearClause(
1412 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1413 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001414 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001415 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1416 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1417 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1418 for (auto *C : LoopDirective->counters()) {
1419 SIMDLCVs.insert(
1420 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1421 }
1422 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001423 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001424 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001425 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001426 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1427 auto *PrivateVD =
1428 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001429 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1430 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1431 // Emit private VarDecl with copy init.
1432 EmitVarDecl(*PrivateVD);
1433 return GetAddrOfLocalVar(PrivateVD);
1434 });
1435 assert(IsRegistered && "linear var already registered as private");
1436 // Silence the warning about unused variable.
1437 (void)IsRegistered;
1438 } else
1439 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001440 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001441 }
1442 }
1443}
1444
Alexey Bataev45bfad52015-08-21 12:19:04 +00001445static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001446 const OMPExecutableDirective &D,
1447 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001448 if (!CGF.HaveInsertPoint())
1449 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001450 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001451 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1452 /*ignoreResult=*/true);
1453 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1454 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1455 // In presence of finite 'safelen', it may be unsafe to mark all
1456 // the memory instructions parallel, because loop-carried
1457 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001458 if (!IsMonotonic)
1459 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001460 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001461 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1462 /*ignoreResult=*/true);
1463 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001464 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001465 // In presence of finite 'safelen', it may be unsafe to mark all
1466 // the memory instructions parallel, because loop-carried
1467 // dependences of 'safelen' iterations are possible.
1468 CGF.LoopStack.setParallel(false);
1469 }
1470}
1471
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001472void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1473 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001474 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001475 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001476 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001477 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001478}
1479
Alexey Bataevef549a82016-03-09 09:49:09 +00001480void CodeGenFunction::EmitOMPSimdFinal(
1481 const OMPLoopDirective &D,
1482 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001483 if (!HaveInsertPoint())
1484 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001485 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001486 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001487 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001488 for (auto F : D.finals()) {
1489 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001490 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1491 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1492 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1493 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001494 if (!DoneBB) {
1495 if (auto *Cond = CondGen(*this)) {
1496 // If the first post-update expression is found, emit conditional
1497 // block if it was requested.
1498 auto *ThenBB = createBasicBlock(".omp.final.then");
1499 DoneBB = createBasicBlock(".omp.final.done");
1500 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1501 EmitBlock(ThenBB);
1502 }
1503 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001504 Address OrigAddr = Address::invalid();
1505 if (CED)
1506 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1507 else {
1508 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1509 /*RefersToEnclosingVariableOrCapture=*/false,
1510 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1511 OrigAddr = EmitLValue(&DRE).getAddress();
1512 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001513 OMPPrivateScope VarScope(*this);
1514 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001515 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001516 (void)VarScope.Privatize();
1517 EmitIgnoredExpr(F);
1518 }
1519 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001520 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001521 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001522 if (DoneBB)
1523 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001524}
1525
Alexander Musman515ad8c2014-05-22 08:54:05 +00001526void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001527 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001528 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001529 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001530 // for (IV in 0..LastIteration) BODY;
1531 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001532 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001533 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001534
Alexey Bataev62dbb972015-04-22 11:59:37 +00001535 // Emit: if (PreCond) - begin.
1536 // If the condition constant folds and can be elided, avoid emitting the
1537 // whole loop.
1538 bool CondConstant;
1539 llvm::BasicBlock *ContBlock = nullptr;
1540 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1541 if (!CondConstant)
1542 return;
1543 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001544 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1545 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001546 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1547 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001548 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001549 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001550 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001551
1552 // Emit the loop iteration variable.
1553 const Expr *IVExpr = S.getIterationVariable();
1554 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1555 CGF.EmitVarDecl(*IVDecl);
1556 CGF.EmitIgnoredExpr(S.getInit());
1557
1558 // Emit the iterations count variable.
1559 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001560 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001561 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1562 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1563 // Emit calculation of the iterations count.
1564 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001565 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001566
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001567 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001568
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001569 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001570 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001571 {
1572 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001573 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1574 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001575 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001576 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001577 bool HasLastprivateClause =
1578 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001579 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001580 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1581 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001582 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001583 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001584 CGF.EmitStopPoint(&S);
1585 },
1586 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001587 CGF.EmitOMPSimdFinal(
1588 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001589 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001590 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001591 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001592 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001593 emitPostUpdateForReductionClause(
1594 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001595 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001596 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001597 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001598 // Emit: if (PreCond) - end.
1599 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001600 CGF.EmitBranch(ContBlock);
1601 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001602 }
1603 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001604 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001605 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001606}
1607
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001608void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001609 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1610 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001611 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001612
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001613 const Expr *IVExpr = S.getIterationVariable();
1614 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1615 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1616
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001617 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1618
1619 // Start the loop with a block that tests the condition.
1620 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1621 EmitBlock(CondBlock);
1622 LoopStack.push(CondBlock);
1623
1624 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001625 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001626 // UB = min(UB, GlobalUB)
1627 EmitIgnoredExpr(S.getEnsureUpperBound());
1628 // IV = LB
1629 EmitIgnoredExpr(S.getInit());
1630 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001631 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001632 } else {
1633 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1634 IL, LB, UB, ST);
1635 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001636
1637 // If there are any cleanups between here and the loop-exit scope,
1638 // create a block to stage a loop exit along.
1639 auto ExitBlock = LoopExit.getBlock();
1640 if (LoopScope.requiresCleanups())
1641 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1642
1643 auto LoopBody = createBasicBlock("omp.dispatch.body");
1644 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1645 if (ExitBlock != LoopExit.getBlock()) {
1646 EmitBlock(ExitBlock);
1647 EmitBranchThroughCleanup(LoopExit);
1648 }
1649 EmitBlock(LoopBody);
1650
Alexander Musman92bdaab2015-03-12 13:37:50 +00001651 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1652 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001653 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001654 EmitIgnoredExpr(S.getInit());
1655
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001656 // Create a block for the increment.
1657 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1658 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1659
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001660 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1661 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001662 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1663 LoopStack.setParallel(!IsMonotonic);
1664 else
1665 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001666
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001667 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001668 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1669 [&S, LoopExit](CodeGenFunction &CGF) {
1670 CGF.EmitOMPLoopBody(S, LoopExit);
1671 CGF.EmitStopPoint(&S);
1672 },
1673 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1674 if (Ordered) {
1675 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1676 CGF, Loc, IVSize, IVSigned);
1677 }
1678 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001679
1680 EmitBlock(Continue.getBlock());
1681 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001682 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683 // Emit "LB = LB + Stride", "UB = UB + Stride".
1684 EmitIgnoredExpr(S.getNextLowerBound());
1685 EmitIgnoredExpr(S.getNextUpperBound());
1686 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001687
1688 EmitBranch(CondBlock);
1689 LoopStack.pop();
1690 // Emit the fall-through block.
1691 EmitBlock(LoopExit.getBlock());
1692
1693 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001694 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001695 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001696
1697}
1698
1699void CodeGenFunction::EmitOMPForOuterLoop(
1700 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1701 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1702 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1703 auto &RT = CGM.getOpenMPRuntime();
1704
1705 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1706 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1707
1708 assert((Ordered ||
1709 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1710 "static non-chunked schedule does not need outer loop");
1711
1712 // Emit outer loop.
1713 //
1714 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1715 // When schedule(dynamic,chunk_size) is specified, the iterations are
1716 // distributed to threads in the team in chunks as the threads request them.
1717 // Each thread executes a chunk of iterations, then requests another chunk,
1718 // until no chunks remain to be distributed. Each chunk contains chunk_size
1719 // iterations, except for the last chunk to be distributed, which may have
1720 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1721 //
1722 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1723 // to threads in the team in chunks as the executing threads request them.
1724 // Each thread executes a chunk of iterations, then requests another chunk,
1725 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1726 // each chunk is proportional to the number of unassigned iterations divided
1727 // by the number of threads in the team, decreasing to 1. For a chunk_size
1728 // with value k (greater than 1), the size of each chunk is determined in the
1729 // same way, with the restriction that the chunks do not contain fewer than k
1730 // iterations (except for the last chunk to be assigned, which may have fewer
1731 // than k iterations).
1732 //
1733 // When schedule(auto) is specified, the decision regarding scheduling is
1734 // delegated to the compiler and/or runtime system. The programmer gives the
1735 // implementation the freedom to choose any possible mapping of iterations to
1736 // threads in the team.
1737 //
1738 // When schedule(runtime) is specified, the decision regarding scheduling is
1739 // deferred until run time, and the schedule and chunk size are taken from the
1740 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1741 // implementation defined
1742 //
1743 // while(__kmpc_dispatch_next(&LB, &UB)) {
1744 // idx = LB;
1745 // while (idx <= UB) { BODY; ++idx;
1746 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1747 // } // inner loop
1748 // }
1749 //
1750 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1751 // When schedule(static, chunk_size) is specified, iterations are divided into
1752 // chunks of size chunk_size, and the chunks are assigned to the threads in
1753 // the team in a round-robin fashion in the order of the thread number.
1754 //
1755 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1756 // while (idx <= UB) { BODY; ++idx; } // inner loop
1757 // LB = LB + ST;
1758 // UB = UB + ST;
1759 // }
1760 //
1761
1762 const Expr *IVExpr = S.getIterationVariable();
1763 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1764 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1765
1766 if (DynamicOrOrdered) {
1767 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1768 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1769 IVSize, IVSigned, Ordered, UBVal, Chunk);
1770 } else {
1771 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1772 Ordered, IL, LB, UB, ST, Chunk);
1773 }
1774
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001775 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001776 ST, IL, Chunk);
1777}
1778
1779void CodeGenFunction::EmitOMPDistributeOuterLoop(
1780 OpenMPDistScheduleClauseKind ScheduleKind,
1781 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1782 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1783
1784 auto &RT = CGM.getOpenMPRuntime();
1785
1786 // Emit outer loop.
1787 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1788 // dynamic
1789 //
1790
1791 const Expr *IVExpr = S.getIterationVariable();
1792 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1793 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1794
1795 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1796 IVSize, IVSigned, /* Ordered = */ false,
1797 IL, LB, UB, ST, Chunk);
1798
1799 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1800 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001801}
1802
Alexander Musmanc6388682014-12-15 07:07:06 +00001803/// \brief Emit a helper variable and return corresponding lvalue.
1804static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1805 const DeclRefExpr *Helper) {
1806 auto VDecl = cast<VarDecl>(Helper->getDecl());
1807 CGF.EmitVarDecl(*VDecl);
1808 return CGF.EmitLValue(Helper);
1809}
1810
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001811namespace {
1812 struct ScheduleKindModifiersTy {
1813 OpenMPScheduleClauseKind Kind;
1814 OpenMPScheduleClauseModifier M1;
1815 OpenMPScheduleClauseModifier M2;
1816 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1817 OpenMPScheduleClauseModifier M1,
1818 OpenMPScheduleClauseModifier M2)
1819 : Kind(Kind), M1(M1), M2(M2) {}
1820 };
1821} // namespace
1822
Alexey Bataev38e89532015-04-16 04:54:05 +00001823bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001824 // Emit the loop iteration variable.
1825 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1826 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1827 EmitVarDecl(*IVDecl);
1828
1829 // Emit the iterations count variable.
1830 // If it is not a variable, Sema decided to calculate iterations count on each
1831 // iteration (e.g., it is foldable into a constant).
1832 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1833 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1834 // Emit calculation of the iterations count.
1835 EmitIgnoredExpr(S.getCalcLastIteration());
1836 }
1837
1838 auto &RT = CGM.getOpenMPRuntime();
1839
Alexey Bataev38e89532015-04-16 04:54:05 +00001840 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001841 // Check pre-condition.
1842 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001843 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001844 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001845 // If the condition constant folds and can be elided, avoid emitting the
1846 // whole loop.
1847 bool CondConstant;
1848 llvm::BasicBlock *ContBlock = nullptr;
1849 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1850 if (!CondConstant)
1851 return false;
1852 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001853 auto *ThenBlock = createBasicBlock("omp.precond.then");
1854 ContBlock = createBasicBlock("omp.precond.end");
1855 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001856 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001857 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001858 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001859 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001860
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001861 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001862 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001863 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001864 // Emit helper vars inits.
1865 LValue LB =
1866 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1867 LValue UB =
1868 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1869 LValue ST =
1870 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1871 LValue IL =
1872 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1873
Alexander Musmanc6388682014-12-15 07:07:06 +00001874 // Emit 'then' code.
1875 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001876 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001877 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1878 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001879 // initialization of firstprivate variables and post-update of
1880 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001881 CGM.getOpenMPRuntime().emitBarrierCall(
1882 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1883 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001884 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001885 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001886 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001887 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001888 EmitOMPPrivateLoopCounters(S, LoopScope);
1889 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001890 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001891
1892 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001893 llvm::Value *Chunk = nullptr;
1894 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1895 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1896 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1897 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1898 ScheduleKind = C->getScheduleKind();
1899 M1 = C->getFirstScheduleModifier();
1900 M2 = C->getSecondScheduleModifier();
1901 if (const auto *Ch = C->getChunkSize()) {
1902 Chunk = EmitScalarExpr(Ch);
1903 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1904 S.getIterationVariable()->getType(),
1905 S.getLocStart());
1906 }
1907 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001908 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1909 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001910 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001911 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1912 // If the static schedule kind is specified or if the ordered clause is
1913 // specified, and if no monotonic modifier is specified, the effect will
1914 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001915 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001916 /* Chunked */ Chunk != nullptr) &&
1917 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001918 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1919 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001920 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1921 // When no chunk_size is specified, the iteration space is divided into
1922 // chunks that are approximately equal in size, and at most one chunk is
1923 // distributed to each thread. Note that the size of the chunks is
1924 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001925 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1926 IVSize, IVSigned, Ordered,
1927 IL.getAddress(), LB.getAddress(),
1928 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001929 auto LoopExit =
1930 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001931 // UB = min(UB, GlobalUB);
1932 EmitIgnoredExpr(S.getEnsureUpperBound());
1933 // IV = LB;
1934 EmitIgnoredExpr(S.getInit());
1935 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001936 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1937 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001938 [&S, LoopExit](CodeGenFunction &CGF) {
1939 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001940 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001941 },
1942 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001943 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001944 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001945 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001946 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001947 const bool IsMonotonic = Ordered ||
1948 ScheduleKind == OMPC_SCHEDULE_static ||
1949 ScheduleKind == OMPC_SCHEDULE_unknown ||
1950 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1951 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001952 // Emit the outer loop, which requests its work chunk [LB..UB] from
1953 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001954 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001955 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1956 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001957 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001958 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1959 EmitOMPSimdFinal(S,
1960 [&](CodeGenFunction &CGF) -> llvm::Value * {
1961 return CGF.Builder.CreateIsNotNull(
1962 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1963 });
1964 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001965 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001966 // Emit post-update of the reduction variables if IsLastIter != 0.
1967 emitPostUpdateForReductionClause(
1968 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1969 return CGF.Builder.CreateIsNotNull(
1970 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1971 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001972 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1973 if (HasLastprivateClause)
1974 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001975 S, isOpenMPSimdDirective(S.getDirectiveKind()),
1976 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001977 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001978 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00001979 return CGF.Builder.CreateIsNotNull(
1980 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1981 });
Alexander Musmanc6388682014-12-15 07:07:06 +00001982 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001983 if (ContBlock) {
1984 EmitBranch(ContBlock);
1985 EmitBlock(ContBlock, true);
1986 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001987 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001988 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001989}
1990
1991void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001992 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001993 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
1994 PrePostActionTy &) {
1995 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1996 };
Alexey Bataev3392d762016-02-16 11:18:12 +00001997 {
1998 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00001999 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2000 S.hasCancel());
2001 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002002
2003 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002004 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002005 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2006 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002007}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002008
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002009void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002010 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002011 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2012 PrePostActionTy &) {
2013 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2014 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002015 {
2016 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00002017 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2018 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002019
2020 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002021 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002022 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2023 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002024}
2025
Alexey Bataev2df54a02015-03-12 08:53:29 +00002026static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2027 const Twine &Name,
2028 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002029 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002030 if (Init)
2031 CGF.EmitScalarInit(Init, LVal);
2032 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002033}
2034
Alexey Bataev3392d762016-02-16 11:18:12 +00002035void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002036 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2037 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002038 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002039 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2040 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002041 auto &C = CGF.CGM.getContext();
2042 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2043 // Emit helper vars inits.
2044 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2045 CGF.Builder.getInt32(0));
2046 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2047 : CGF.Builder.getInt32(0);
2048 LValue UB =
2049 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2050 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2051 CGF.Builder.getInt32(1));
2052 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2053 CGF.Builder.getInt32(0));
2054 // Loop counter.
2055 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2056 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2057 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2058 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2059 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2060 // Generate condition for loop.
2061 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2062 OK_Ordinary, S.getLocStart(),
2063 /*fpContractable=*/false);
2064 // Increment for loop counter.
2065 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2066 S.getLocStart());
2067 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2068 // Iterate through all sections and emit a switch construct:
2069 // switch (IV) {
2070 // case 0:
2071 // <SectionStmt[0]>;
2072 // break;
2073 // ...
2074 // case <NumSection> - 1:
2075 // <SectionStmt[<NumSection> - 1]>;
2076 // break;
2077 // }
2078 // .omp.sections.exit:
2079 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2080 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2081 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2082 CS == nullptr ? 1 : CS->size());
2083 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002084 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002085 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002086 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2087 CGF.EmitBlock(CaseBB);
2088 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002089 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002090 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002091 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002092 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002093 } else {
2094 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2095 CGF.EmitBlock(CaseBB);
2096 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2097 CGF.EmitStmt(Stmt);
2098 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002099 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002100 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002101 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002102
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002103 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2104 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002105 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002106 // initialization of firstprivate variables and post-update of lastprivate
2107 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002108 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2109 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2110 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002111 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002112 CGF.EmitOMPPrivateClause(S, LoopScope);
2113 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2114 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2115 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002116
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002117 // Emit static non-chunked loop.
2118 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2119 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
2120 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2121 UB.getAddress(), ST.getAddress());
2122 // UB = min(UB, GlobalUB);
2123 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2124 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2125 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2126 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2127 // IV = LB;
2128 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2129 // while (idx <= UB) { BODY; ++idx; }
2130 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2131 [](CodeGenFunction &) {});
2132 // Tell the runtime we are done.
2133 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2134 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002135 // Emit post-update of the reduction variables if IsLastIter != 0.
2136 emitPostUpdateForReductionClause(
2137 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2138 return CGF.Builder.CreateIsNotNull(
2139 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2140 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002141
2142 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2143 if (HasLastprivates)
2144 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002145 S, /*NoFinals=*/false,
2146 CGF.Builder.CreateIsNotNull(
2147 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002148 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002149
2150 bool HasCancel = false;
2151 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2152 HasCancel = OSD->hasCancel();
2153 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2154 HasCancel = OPSD->hasCancel();
2155 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2156 HasCancel);
2157 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2158 // clause. Otherwise the barrier will be generated by the codegen for the
2159 // directive.
2160 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002161 // Emit implicit barrier to synchronize threads and avoid data races on
2162 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002163 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2164 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002165 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002166}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002167
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002168void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002169 {
2170 OMPLexicalScope Scope(*this, S);
2171 EmitSections(S);
2172 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002173 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002174 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002175 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2176 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002177 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002178}
2179
2180void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002181 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002182 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002183 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002184 OMPLexicalScope Scope(*this, S);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002185 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2186 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002187}
2188
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002189void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002190 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002191 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002192 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002193 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002194 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002195 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002196 // Build a list of copyprivate variables along with helper expressions
2197 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002198 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002199 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002200 DestExprs.append(C->destination_exprs().begin(),
2201 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002202 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002203 AssignmentOps.append(C->assignment_ops().begin(),
2204 C->assignment_ops().end());
2205 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002206 // Emit code for 'single' region along with 'copyprivate' clauses
2207 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2208 Action.Enter(CGF);
2209 OMPPrivateScope SingleScope(CGF);
2210 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2211 CGF.EmitOMPPrivateClause(S, SingleScope);
2212 (void)SingleScope.Privatize();
2213 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2214 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002215 {
2216 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00002217 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2218 CopyprivateVars, DestExprs,
2219 SrcExprs, AssignmentOps);
2220 }
2221 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2222 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002223 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002224 CGM.getOpenMPRuntime().emitBarrierCall(
2225 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002226 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002227 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002228}
2229
Alexey Bataev8d690652014-12-04 07:23:53 +00002230void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002231 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2232 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002233 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002234 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002235 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002236 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002237}
2238
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002239void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002240 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2241 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002242 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002243 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002244 Expr *Hint = nullptr;
2245 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2246 Hint = HintClause->getHint();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002247 OMPLexicalScope Scope(*this, S);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002248 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2249 S.getDirectiveName().getAsString(),
2250 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002251}
2252
Alexey Bataev671605e2015-04-13 05:28:11 +00002253void CodeGenFunction::EmitOMPParallelForDirective(
2254 const OMPParallelForDirective &S) {
2255 // Emit directive as a combined directive that consists of two implicit
2256 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002257 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002258 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002259 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002260 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002261}
2262
Alexander Musmane4e893b2014-09-23 09:33:00 +00002263void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002264 const OMPParallelForSimdDirective &S) {
2265 // Emit directive as a combined directive that consists of two implicit
2266 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002267 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002268 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002269 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002270 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002271}
2272
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002273void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002274 const OMPParallelSectionsDirective &S) {
2275 // Emit directive as a combined directive that consists of two implicit
2276 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002277 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2278 CGF.EmitSections(S);
2279 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002280 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002281}
2282
Alexey Bataev62b63b12015-03-10 07:28:44 +00002283void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2284 // Emit outlined function for task construct.
2285 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2286 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2287 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002288 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002289 auto *TaskT = std::next(I, 4);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002290 // The first function argument for tasks is a thread id, the second one is a
2291 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002292 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2293 // Get list of private variables.
2294 llvm::SmallVector<const Expr *, 8> PrivateVars;
2295 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002296 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002297 auto IRef = C->varlist_begin();
2298 for (auto *IInit : C->private_copies()) {
2299 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2300 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2301 PrivateVars.push_back(*IRef);
2302 PrivateCopies.push_back(IInit);
2303 }
2304 ++IRef;
2305 }
2306 }
2307 EmittedAsPrivate.clear();
2308 // Get list of firstprivate variables.
2309 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2310 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2311 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002312 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002313 auto IRef = C->varlist_begin();
2314 auto IElemInitRef = C->inits().begin();
2315 for (auto *IInit : C->private_copies()) {
2316 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2317 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2318 FirstprivateVars.push_back(*IRef);
2319 FirstprivateCopies.push_back(IInit);
2320 FirstprivateInits.push_back(*IElemInitRef);
2321 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002322 ++IRef;
2323 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002324 }
2325 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002326 // Build list of dependences.
2327 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2328 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002329 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002330 for (auto *IRef : C->varlists()) {
2331 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2332 }
2333 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002334 auto &&CodeGen = [&S, &PrivateVars, &FirstprivateVars](
2335 CodeGenFunction &CGF, PrePostActionTy &Action) {
2336 OMPPrivateScope Scope(CGF);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002337 // Set proper addresses for generated private copies.
2338 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002339 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
2340 auto *CopyFn = CGF.Builder.CreateLoad(
2341 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2342 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2343 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2344 // Map privates.
2345 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2346 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2347 CallArgs.push_back(PrivatesPtr);
2348 for (auto *E : PrivateVars) {
2349 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2350 Address PrivatePtr = CGF.CreateMemTemp(
2351 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2352 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2353 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002354 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002355 for (auto *E : FirstprivateVars) {
2356 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2357 Address PrivatePtr =
2358 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2359 ".firstpriv.ptr.addr");
2360 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2361 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002362 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002363 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2364 for (auto &&Pair : PrivatePtrs) {
2365 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2366 CGF.getContext().getDeclAlign(Pair.first));
2367 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2368 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002369 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002370 (void)Scope.Privatize();
2371
2372 Action.Enter(CGF);
2373 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002374 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00002375 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002376 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002377 unsigned NumberOfParts;
2378 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2379 S, *I, *PartId, *TaskT, OMPD_task, CodeGen, Tied, NumberOfParts);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002380 // Check if the task is final
2381 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002382 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002383 // If the condition constant folds and can be elided, try to avoid emitting
2384 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002385 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002386 bool CondConstant;
2387 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2388 Final.setInt(CondConstant);
2389 else
2390 Final.setPointer(EvaluateExprAsBool(Cond));
2391 } else {
2392 // By default the task is not final.
2393 Final.setInt(/*IntVal=*/false);
2394 }
2395 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002396 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002397 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2398 if (C->getNameModifier() == OMPD_unknown ||
2399 C->getNameModifier() == OMPD_task) {
2400 IfCond = C->getCondition();
2401 break;
2402 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002403 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002404 OMPLexicalScope Scope(*this, S);
Alexey Bataev9e034042015-05-05 04:05:12 +00002405 CGM.getOpenMPRuntime().emitTaskCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00002406 *this, S.getLocStart(), S, Tied, Final, NumberOfParts, OutlinedFn,
2407 SharedsTy, CapturedStruct, IfCond, PrivateVars, PrivateCopies,
2408 FirstprivateVars, FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002409}
2410
Alexey Bataev9f797f32015-02-05 05:57:51 +00002411void CodeGenFunction::EmitOMPTaskyieldDirective(
2412 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002413 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002414}
2415
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002416void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002417 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002418}
2419
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002420void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2421 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002422}
2423
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002424void CodeGenFunction::EmitOMPTaskgroupDirective(
2425 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002426 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2427 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002428 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002429 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002431 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2432}
2433
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002434void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002435 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002436 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002437 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2438 FlushClause->varlist_end());
2439 }
2440 return llvm::None;
2441 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002442}
2443
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002444void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2445 // Emit the loop iteration variable.
2446 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2447 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2448 EmitVarDecl(*IVDecl);
2449
2450 // Emit the iterations count variable.
2451 // If it is not a variable, Sema decided to calculate iterations count on each
2452 // iteration (e.g., it is foldable into a constant).
2453 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2454 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2455 // Emit calculation of the iterations count.
2456 EmitIgnoredExpr(S.getCalcLastIteration());
2457 }
2458
2459 auto &RT = CGM.getOpenMPRuntime();
2460
2461 // Check pre-condition.
2462 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002463 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002464 // Skip the entire loop if we don't meet the precondition.
2465 // If the condition constant folds and can be elided, avoid emitting the
2466 // whole loop.
2467 bool CondConstant;
2468 llvm::BasicBlock *ContBlock = nullptr;
2469 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2470 if (!CondConstant)
2471 return;
2472 } else {
2473 auto *ThenBlock = createBasicBlock("omp.precond.then");
2474 ContBlock = createBasicBlock("omp.precond.end");
2475 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2476 getProfileCount(&S));
2477 EmitBlock(ThenBlock);
2478 incrementProfileCounter(&S);
2479 }
2480
2481 // Emit 'then' code.
2482 {
2483 // Emit helper vars inits.
2484 LValue LB =
2485 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2486 LValue UB =
2487 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2488 LValue ST =
2489 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2490 LValue IL =
2491 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2492
2493 OMPPrivateScope LoopScope(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002494 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002495 (void)LoopScope.Privatize();
2496
2497 // Detect the distribute schedule kind and chunk.
2498 llvm::Value *Chunk = nullptr;
2499 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2500 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2501 ScheduleKind = C->getDistScheduleKind();
2502 if (const auto *Ch = C->getChunkSize()) {
2503 Chunk = EmitScalarExpr(Ch);
2504 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2505 S.getIterationVariable()->getType(),
2506 S.getLocStart());
2507 }
2508 }
2509 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2510 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2511
2512 // OpenMP [2.10.8, distribute Construct, Description]
2513 // If dist_schedule is specified, kind must be static. If specified,
2514 // iterations are divided into chunks of size chunk_size, chunks are
2515 // assigned to the teams of the league in a round-robin fashion in the
2516 // order of the team number. When no chunk_size is specified, the
2517 // iteration space is divided into chunks that are approximately equal
2518 // in size, and at most one chunk is distributed to each team of the
2519 // league. The size of the chunks is unspecified in this case.
2520 if (RT.isStaticNonchunked(ScheduleKind,
2521 /* Chunked */ Chunk != nullptr)) {
2522 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2523 IVSize, IVSigned, /* Ordered = */ false,
2524 IL.getAddress(), LB.getAddress(),
2525 UB.getAddress(), ST.getAddress());
2526 auto LoopExit =
2527 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2528 // UB = min(UB, GlobalUB);
2529 EmitIgnoredExpr(S.getEnsureUpperBound());
2530 // IV = LB;
2531 EmitIgnoredExpr(S.getInit());
2532 // while (idx <= UB) { BODY; ++idx; }
2533 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2534 S.getInc(),
2535 [&S, LoopExit](CodeGenFunction &CGF) {
2536 CGF.EmitOMPLoopBody(S, LoopExit);
2537 CGF.EmitStopPoint(&S);
2538 },
2539 [](CodeGenFunction &) {});
2540 EmitBlock(LoopExit.getBlock());
2541 // Tell the runtime we are done.
2542 RT.emitForStaticFinish(*this, S.getLocStart());
2543 } else {
2544 // Emit the outer loop, which requests its work chunk [LB..UB] from
2545 // runtime and runs the inner loop to process it.
2546 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2547 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2548 IL.getAddress(), Chunk);
2549 }
2550 }
2551
2552 // We're now done with the loop, so jump to the continuation block.
2553 if (ContBlock) {
2554 EmitBranch(ContBlock);
2555 EmitBlock(ContBlock, true);
2556 }
2557 }
2558}
2559
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002560void CodeGenFunction::EmitOMPDistributeDirective(
2561 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002563 CGF.EmitOMPDistributeLoop(S);
2564 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002565 OMPLexicalScope Scope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002566 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2567 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002568}
2569
Alexey Bataev5f600d62015-09-29 03:48:57 +00002570static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2571 const CapturedStmt *S) {
2572 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2573 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2574 CGF.CapturedStmtInfo = &CapStmtInfo;
2575 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2576 Fn->addFnAttr(llvm::Attribute::NoInline);
2577 return Fn;
2578}
2579
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002580void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!S.getAssociatedStmt())
2582 return;
Alexey Bataev5f600d62015-09-29 03:48:57 +00002583 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002584 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2585 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002586 if (C) {
2587 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2588 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2589 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2590 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2591 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2592 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002593 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002594 CGF.EmitStmt(
2595 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2596 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002597 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002598 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002599 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002600}
2601
Alexey Bataevb57056f2015-01-22 06:17:56 +00002602static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002603 QualType SrcType, QualType DestType,
2604 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002605 assert(CGF.hasScalarEvaluationKind(DestType) &&
2606 "DestType must have scalar evaluation kind.");
2607 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2608 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002609 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2610 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002611 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002612 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002613}
2614
2615static CodeGenFunction::ComplexPairTy
2616convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002617 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002618 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2619 "DestType must have complex evaluation kind.");
2620 CodeGenFunction::ComplexPairTy ComplexVal;
2621 if (Val.isScalar()) {
2622 // Convert the input element to the element type of the complex.
2623 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002624 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2625 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002626 ComplexVal = CodeGenFunction::ComplexPairTy(
2627 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2628 } else {
2629 assert(Val.isComplex() && "Must be a scalar or complex.");
2630 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2631 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2632 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002633 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002634 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002635 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002636 }
2637 return ComplexVal;
2638}
2639
Alexey Bataev5e018f92015-04-23 06:35:10 +00002640static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2641 LValue LVal, RValue RVal) {
2642 if (LVal.isGlobalReg()) {
2643 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2644 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002645 CGF.EmitAtomicStore(RVal, LVal,
2646 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2647 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002648 LVal.isVolatile(), /*IsInit=*/false);
2649 }
2650}
2651
Alexey Bataev8524d152016-01-21 12:35:58 +00002652void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2653 QualType RValTy, SourceLocation Loc) {
2654 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002655 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002656 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2657 *this, RVal, RValTy, LVal.getType(), Loc)),
2658 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002659 break;
2660 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002661 EmitStoreOfComplex(
2662 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002663 /*isInit=*/false);
2664 break;
2665 case TEK_Aggregate:
2666 llvm_unreachable("Must be a scalar or complex.");
2667 }
2668}
2669
Alexey Bataevb57056f2015-01-22 06:17:56 +00002670static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2671 const Expr *X, const Expr *V,
2672 SourceLocation Loc) {
2673 // v = x;
2674 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2675 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2676 LValue XLValue = CGF.EmitLValue(X);
2677 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002678 RValue Res = XLValue.isGlobalReg()
2679 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00002680 : CGF.EmitAtomicLoad(
2681 XLValue, Loc,
2682 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2683 : llvm::AtomicOrdering::Monotonic,
2684 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002685 // OpenMP, 2.12.6, atomic Construct
2686 // Any atomic construct with a seq_cst clause forces the atomically
2687 // performed operation to include an implicit flush operation without a
2688 // list.
2689 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002690 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002691 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002692}
2693
Alexey Bataevb8329262015-02-27 06:33:30 +00002694static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2695 const Expr *X, const Expr *E,
2696 SourceLocation Loc) {
2697 // x = expr;
2698 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002699 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002700 // OpenMP, 2.12.6, atomic Construct
2701 // Any atomic construct with a seq_cst clause forces the atomically
2702 // performed operation to include an implicit flush operation without a
2703 // list.
2704 if (IsSeqCst)
2705 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2706}
2707
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002708static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2709 RValue Update,
2710 BinaryOperatorKind BO,
2711 llvm::AtomicOrdering AO,
2712 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002713 auto &Context = CGF.CGM.getContext();
2714 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002715 // expression is simple and atomic is allowed for the given type for the
2716 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002717 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002718 !Update.getScalarVal()->getType()->isIntegerTy() ||
2719 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2720 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002721 X.getAddress().getElementType())) ||
2722 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002723 !Context.getTargetInfo().hasBuiltinAtomic(
2724 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002725 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002726
2727 llvm::AtomicRMWInst::BinOp RMWOp;
2728 switch (BO) {
2729 case BO_Add:
2730 RMWOp = llvm::AtomicRMWInst::Add;
2731 break;
2732 case BO_Sub:
2733 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002734 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002735 RMWOp = llvm::AtomicRMWInst::Sub;
2736 break;
2737 case BO_And:
2738 RMWOp = llvm::AtomicRMWInst::And;
2739 break;
2740 case BO_Or:
2741 RMWOp = llvm::AtomicRMWInst::Or;
2742 break;
2743 case BO_Xor:
2744 RMWOp = llvm::AtomicRMWInst::Xor;
2745 break;
2746 case BO_LT:
2747 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2748 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2749 : llvm::AtomicRMWInst::Max)
2750 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2751 : llvm::AtomicRMWInst::UMax);
2752 break;
2753 case BO_GT:
2754 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2755 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2756 : llvm::AtomicRMWInst::Min)
2757 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2758 : llvm::AtomicRMWInst::UMin);
2759 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002760 case BO_Assign:
2761 RMWOp = llvm::AtomicRMWInst::Xchg;
2762 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002763 case BO_Mul:
2764 case BO_Div:
2765 case BO_Rem:
2766 case BO_Shl:
2767 case BO_Shr:
2768 case BO_LAnd:
2769 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002770 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002771 case BO_PtrMemD:
2772 case BO_PtrMemI:
2773 case BO_LE:
2774 case BO_GE:
2775 case BO_EQ:
2776 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002777 case BO_AddAssign:
2778 case BO_SubAssign:
2779 case BO_AndAssign:
2780 case BO_OrAssign:
2781 case BO_XorAssign:
2782 case BO_MulAssign:
2783 case BO_DivAssign:
2784 case BO_RemAssign:
2785 case BO_ShlAssign:
2786 case BO_ShrAssign:
2787 case BO_Comma:
2788 llvm_unreachable("Unsupported atomic update operation");
2789 }
2790 auto *UpdateVal = Update.getScalarVal();
2791 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2792 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002793 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002794 X.getType()->hasSignedIntegerRepresentation());
2795 }
John McCall7f416cc2015-09-08 08:05:57 +00002796 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002797 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002798}
2799
Alexey Bataev5e018f92015-04-23 06:35:10 +00002800std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002801 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2802 llvm::AtomicOrdering AO, SourceLocation Loc,
2803 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2804 // Update expressions are allowed to have the following forms:
2805 // x binop= expr; -> xrval + expr;
2806 // x++, ++x -> xrval + 1;
2807 // x--, --x -> xrval - 1;
2808 // x = x binop expr; -> xrval binop expr
2809 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002810 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2811 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002812 if (X.isGlobalReg()) {
2813 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2814 // 'xrval'.
2815 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2816 } else {
2817 // Perform compare-and-swap procedure.
2818 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002819 }
2820 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002821 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002822}
2823
2824static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2825 const Expr *X, const Expr *E,
2826 const Expr *UE, bool IsXLHSInRHSPart,
2827 SourceLocation Loc) {
2828 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2829 "Update expr in 'atomic update' must be a binary operator.");
2830 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2831 // Update expressions are allowed to have the following forms:
2832 // x binop= expr; -> xrval + expr;
2833 // x++, ++x -> xrval + 1;
2834 // x--, --x -> xrval - 1;
2835 // x = x binop expr; -> xrval binop expr
2836 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002837 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002838 LValue XLValue = CGF.EmitLValue(X);
2839 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002840 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2841 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002842 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2843 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2844 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2845 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2846 auto Gen =
2847 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2848 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2849 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2850 return CGF.EmitAnyExpr(UE);
2851 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002852 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2853 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2854 // OpenMP, 2.12.6, atomic Construct
2855 // Any atomic construct with a seq_cst clause forces the atomically
2856 // performed operation to include an implicit flush operation without a
2857 // list.
2858 if (IsSeqCst)
2859 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2860}
2861
2862static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002863 QualType SourceType, QualType ResType,
2864 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002865 switch (CGF.getEvaluationKind(ResType)) {
2866 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002867 return RValue::get(
2868 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002869 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002870 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002871 return RValue::getComplex(Res.first, Res.second);
2872 }
2873 case TEK_Aggregate:
2874 break;
2875 }
2876 llvm_unreachable("Must be a scalar or complex.");
2877}
2878
2879static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2880 bool IsPostfixUpdate, const Expr *V,
2881 const Expr *X, const Expr *E,
2882 const Expr *UE, bool IsXLHSInRHSPart,
2883 SourceLocation Loc) {
2884 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2885 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2886 RValue NewVVal;
2887 LValue VLValue = CGF.EmitLValue(V);
2888 LValue XLValue = CGF.EmitLValue(X);
2889 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00002890 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2891 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002892 QualType NewVValType;
2893 if (UE) {
2894 // 'x' is updated with some additional value.
2895 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2896 "Update expr in 'atomic capture' must be a binary operator.");
2897 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2898 // Update expressions are allowed to have the following forms:
2899 // x binop= expr; -> xrval + expr;
2900 // x++, ++x -> xrval + 1;
2901 // x--, --x -> xrval - 1;
2902 // x = x binop expr; -> xrval binop expr
2903 // x = expr Op x; - > expr binop xrval;
2904 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2905 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2906 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2907 NewVValType = XRValExpr->getType();
2908 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2909 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2910 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2911 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2912 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2913 RValue Res = CGF.EmitAnyExpr(UE);
2914 NewVVal = IsPostfixUpdate ? XRValue : Res;
2915 return Res;
2916 };
2917 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2918 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2919 if (Res.first) {
2920 // 'atomicrmw' instruction was generated.
2921 if (IsPostfixUpdate) {
2922 // Use old value from 'atomicrmw'.
2923 NewVVal = Res.second;
2924 } else {
2925 // 'atomicrmw' does not provide new value, so evaluate it using old
2926 // value of 'x'.
2927 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2928 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2929 NewVVal = CGF.EmitAnyExpr(UE);
2930 }
2931 }
2932 } else {
2933 // 'x' is simply rewritten with some 'expr'.
2934 NewVValType = X->getType().getNonReferenceType();
2935 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002936 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002937 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2938 NewVVal = XRValue;
2939 return ExprRValue;
2940 };
2941 // Try to perform atomicrmw xchg, otherwise simple exchange.
2942 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2943 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2944 Loc, Gen);
2945 if (Res.first) {
2946 // 'atomicrmw' instruction was generated.
2947 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2948 }
2949 }
2950 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002951 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002952 // OpenMP, 2.12.6, atomic Construct
2953 // Any atomic construct with a seq_cst clause forces the atomically
2954 // performed operation to include an implicit flush operation without a
2955 // list.
2956 if (IsSeqCst)
2957 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2958}
2959
Alexey Bataevb57056f2015-01-22 06:17:56 +00002960static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002961 bool IsSeqCst, bool IsPostfixUpdate,
2962 const Expr *X, const Expr *V, const Expr *E,
2963 const Expr *UE, bool IsXLHSInRHSPart,
2964 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002965 switch (Kind) {
2966 case OMPC_read:
2967 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2968 break;
2969 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002970 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2971 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002972 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002973 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002974 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2975 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002976 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002977 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2978 IsXLHSInRHSPart, Loc);
2979 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002980 case OMPC_if:
2981 case OMPC_final:
2982 case OMPC_num_threads:
2983 case OMPC_private:
2984 case OMPC_firstprivate:
2985 case OMPC_lastprivate:
2986 case OMPC_reduction:
2987 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002988 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002989 case OMPC_collapse:
2990 case OMPC_default:
2991 case OMPC_seq_cst:
2992 case OMPC_shared:
2993 case OMPC_linear:
2994 case OMPC_aligned:
2995 case OMPC_copyin:
2996 case OMPC_copyprivate:
2997 case OMPC_flush:
2998 case OMPC_proc_bind:
2999 case OMPC_schedule:
3000 case OMPC_ordered:
3001 case OMPC_nowait:
3002 case OMPC_untied:
3003 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003004 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003005 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003006 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003007 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003008 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003009 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003010 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003011 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003012 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003013 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003014 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003015 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003016 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003017 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003018 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003019 case OMPC_uniform:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003020 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3021 }
3022}
3023
3024void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003025 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003026 OpenMPClauseKind Kind = OMPC_unknown;
3027 for (auto *C : S.clauses()) {
3028 // Find first clause (skip seq_cst clause, if it is first).
3029 if (C->getClauseKind() != OMPC_seq_cst) {
3030 Kind = C->getClauseKind();
3031 break;
3032 }
3033 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003034
3035 const auto *CS =
3036 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003037 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003038 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003039 }
3040 // Processing for statements under 'atomic capture'.
3041 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3042 for (const auto *C : Compound->body()) {
3043 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3044 enterFullExpression(EWC);
3045 }
3046 }
3047 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003048
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003049 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3050 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003051 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003052 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3053 S.getV(), S.getExpr(), S.getUpdateExpr(),
3054 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003055 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003056 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003057 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003058}
3059
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003060std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
3061CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
3062 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
3063 bool IsOffloadEntry) {
3064 llvm::Function *OutlinedFn = nullptr;
3065 llvm::Constant *OutlinedFnID = nullptr;
3066 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3067 OMPPrivateScope PrivateScope(CGF);
3068 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3069 CGF.EmitOMPPrivateClause(S, PrivateScope);
3070 (void)PrivateScope.Privatize();
3071
3072 Action.Enter(CGF);
3073 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3074 };
3075 // Emit target region as a standalone region.
3076 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3077 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3078 return std::make_pair(OutlinedFn, OutlinedFnID);
3079}
3080
Samuel Antaobed3c462015-10-02 16:14:20 +00003081void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003082 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3083
3084 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003085 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003086
Samuel Antaoee8fb302016-01-06 13:42:12 +00003087 llvm::Function *Fn = nullptr;
3088 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003089
3090 // Check if we have any if clause associated with the directive.
3091 const Expr *IfCond = nullptr;
3092
3093 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3094 IfCond = C->getCondition();
3095 }
3096
3097 // Check if we have any device clause associated with the directive.
3098 const Expr *Device = nullptr;
3099 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3100 Device = C->getDevice();
3101 }
3102
Samuel Antaoee8fb302016-01-06 13:42:12 +00003103 // Check if we have an if clause whose conditional always evaluates to false
3104 // or if we do not have any targets specified. If so the target region is not
3105 // an offload entry point.
3106 bool IsOffloadEntry = true;
3107 if (IfCond) {
3108 bool Val;
3109 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3110 IsOffloadEntry = false;
3111 }
3112 if (CGM.getLangOpts().OMPTargetTriples.empty())
3113 IsOffloadEntry = false;
3114
3115 assert(CurFuncDecl && "No parent declaration for target region!");
3116 StringRef ParentName;
3117 // In case we have Ctors/Dtors we use the complete type variant to produce
3118 // the mangling of the device outlined kernel.
3119 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3120 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3121 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3122 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3123 else
3124 ParentName =
3125 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3126
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003127 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3128 CGM, S, ParentName, IsOffloadEntry);
3129 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003130 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003131 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003132}
3133
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003134static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3135 const OMPExecutableDirective &S,
3136 OpenMPDirectiveKind InnermostKind,
3137 const RegionCodeGenTy &CodeGen) {
3138 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003139 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3140 emitParallelOrTeamsOutlinedFunction(S,
3141 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003142
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003143 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3144 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3145 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3146 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003147 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3148 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003149
Carlo Bertollic6872252016-04-04 15:55:02 +00003150 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3151 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003152 }
3153
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003154 OMPLexicalScope Scope(CGF, S);
3155 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3156 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003157 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3158 CapturedVars);
3159}
3160
3161void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003162 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003163 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003164 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003165 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3166 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003167 (void)PrivateScope.Privatize();
3168 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3169 };
3170 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003171}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003172
3173void CodeGenFunction::EmitOMPCancellationPointDirective(
3174 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003175 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3176 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003177}
3178
Alexey Bataev80909872015-07-02 11:25:17 +00003179void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003180 const Expr *IfCond = nullptr;
3181 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3182 if (C->getNameModifier() == OMPD_unknown ||
3183 C->getNameModifier() == OMPD_cancel) {
3184 IfCond = C->getCondition();
3185 break;
3186 }
3187 }
3188 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003189 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003190}
3191
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003192CodeGenFunction::JumpDest
3193CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3194 if (Kind == OMPD_parallel || Kind == OMPD_task)
3195 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003196 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003197 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003198 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003199}
Michael Wong65f367f2015-07-21 13:44:28 +00003200
3201// Generate the instructions for '#pragma omp target data' directive.
3202void CodeGenFunction::EmitOMPTargetDataDirective(
3203 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00003204 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003205 OMPLexicalScope Scope(*this, S);
Michael Wongb5c16982015-08-11 04:52:01 +00003206 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003207 *this, OMPD_target_data, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3208 CGF.EmitStmt(
3209 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3210 });
Michael Wong65f367f2015-07-21 13:44:28 +00003211}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003212
Samuel Antaodf67fc42016-01-19 19:15:56 +00003213void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3214 const OMPTargetEnterDataDirective &S) {
3215 // TODO: codegen for target enter data.
3216}
3217
Samuel Antao72590762016-01-19 20:04:50 +00003218void CodeGenFunction::EmitOMPTargetExitDataDirective(
3219 const OMPTargetExitDataDirective &S) {
3220 // TODO: codegen for target exit data.
3221}
3222
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003223void CodeGenFunction::EmitOMPTargetParallelDirective(
3224 const OMPTargetParallelDirective &S) {
3225 // TODO: codegen for target parallel.
3226}
3227
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003228void CodeGenFunction::EmitOMPTargetParallelForDirective(
3229 const OMPTargetParallelForDirective &S) {
3230 // TODO: codegen for target parallel for.
3231}
3232
Alexey Bataev49f6e782015-12-01 04:18:41 +00003233void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
3234 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003235 OMPLexicalScope Scope(*this, S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003236 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003237 *this, OMPD_taskloop, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003238 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003239 CGF.EmitStmt(
3240 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3241 });
Alexey Bataev49f6e782015-12-01 04:18:41 +00003242}
3243
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003244void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3245 const OMPTaskLoopSimdDirective &S) {
3246 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003247 OMPLexicalScope Scope(*this, S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003248 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003249 *this, OMPD_taskloop_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003250 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003251 CGF.EmitStmt(
3252 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3253 });
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003254}