blob: 87c9b3b4d1d0dce9ab7c910de24a12331d96028d [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 Bataev3392d762016-02-16 11:18:12 +000055} // namespace
56
Alexey Bataev1189bd02016-01-26 12:20:39 +000057llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
58 auto &C = getContext();
59 llvm::Value *Size = nullptr;
60 auto SizeInChars = C.getTypeSizeInChars(Ty);
61 if (SizeInChars.isZero()) {
62 // getTypeSizeInChars() returns 0 for a VLA.
63 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
64 llvm::Value *ArraySize;
65 std::tie(ArraySize, Ty) = getVLASize(VAT);
66 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
67 }
68 SizeInChars = C.getTypeSizeInChars(Ty);
69 if (SizeInChars.isZero())
70 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
71 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
72 } else
73 Size = CGM.getSize(SizeInChars);
74 return Size;
75}
76
Alexey Bataev2377fe92015-09-10 08:12:02 +000077void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000078 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000079 const RecordDecl *RD = S.getCapturedRecordDecl();
80 auto CurField = RD->field_begin();
81 auto CurCap = S.captures().begin();
82 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
83 E = S.capture_init_end();
84 I != E; ++I, ++CurField, ++CurCap) {
85 if (CurField->hasCapturedVLAType()) {
86 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000087 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000088 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000089 } else if (CurCap->capturesThis())
90 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000091 else if (CurCap->capturesVariableByCopy())
92 CapturedVars.push_back(
93 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
94 else {
95 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000096 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000098 }
99}
100
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000101static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
102 StringRef Name, LValue AddrLV,
103 bool isReferenceType = false) {
104 ASTContext &Ctx = CGF.getContext();
105
106 auto *CastedPtr = CGF.EmitScalarConversion(
107 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
108 Ctx.getPointerType(DstType), SourceLocation());
109 auto TmpAddr =
110 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
111 .getAddress();
112
113 // If we are dealing with references we need to return the address of the
114 // reference instead of the reference of the value.
115 if (isReferenceType) {
116 QualType RefType = Ctx.getLValueReferenceType(DstType);
117 auto *RefVal = TmpAddr.getPointer();
118 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
119 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
120 CGF.EmitScalarInit(RefVal, TmpLVal);
121 }
122
123 return TmpAddr;
124}
125
Alexey Bataev2377fe92015-09-10 08:12:02 +0000126llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000127CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000128 assert(
129 CapturedStmtInfo &&
130 "CapturedStmtInfo should be set when generating the captured function");
131 const CapturedDecl *CD = S.getCapturedDecl();
132 const RecordDecl *RD = S.getCapturedRecordDecl();
133 assert(CD->hasBody() && "missing CapturedDecl body");
134
135 // Build the argument list.
136 ASTContext &Ctx = CGM.getContext();
137 FunctionArgList Args;
138 Args.append(CD->param_begin(),
139 std::next(CD->param_begin(), CD->getContextParamPosition()));
140 auto I = S.captures().begin();
141 for (auto *FD : RD->fields()) {
142 QualType ArgType = FD->getType();
143 IdentifierInfo *II = nullptr;
144 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000145
146 // If this is a capture by copy and the type is not a pointer, the outlined
147 // function argument type should be uintptr and the value properly casted to
148 // uintptr. This is necessary given that the runtime library is only able to
149 // deal with pointers. We can pass in the same way the VLA type sizes to the
150 // outlined function.
151 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
152 I->capturesVariableArrayType())
153 ArgType = Ctx.getUIntPtrType();
154
155 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000156 CapVar = I->getCapturedVar();
157 II = CapVar->getIdentifier();
158 } else if (I->capturesThis())
159 II = &getContext().Idents.get("this");
160 else {
161 assert(I->capturesVariableArrayType());
162 II = &getContext().Idents.get("vla");
163 }
164 if (ArgType->isVariablyModifiedType())
165 ArgType = getContext().getVariableArrayDecayedType(ArgType);
166 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
167 FD->getLocation(), II, ArgType));
168 ++I;
169 }
170 Args.append(
171 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
172 CD->param_end());
173
174 // Create the function declaration.
175 FunctionType::ExtInfo ExtInfo;
176 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000177 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000178 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
179
180 llvm::Function *F = llvm::Function::Create(
181 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
182 CapturedStmtInfo->getHelperName(), &CGM.getModule());
183 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
184 if (CD->isNothrow())
185 F->addFnAttr(llvm::Attribute::NoUnwind);
186
187 // Generate the function.
188 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
189 CD->getBody()->getLocStart());
190 unsigned Cnt = CD->getContextParamPosition();
191 I = S.captures().begin();
192 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193 // If we are capturing a pointer by copy we don't need to do anything, just
194 // use the value that we get from the arguments.
195 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
196 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000197 ++Cnt;
198 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 continue;
200 }
201
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 LValue ArgLVal =
203 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
204 AlignmentSource::Decl);
205 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206 LValue CastedArgLVal =
207 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
208 Args[Cnt]->getName(), ArgLVal),
209 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000210 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000211 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000212 auto VAT = FD->getCapturedVLAType();
213 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
214 } else if (I->capturesVariable()) {
215 auto *Var = I->getCapturedVar();
216 QualType VarTy = Var->getType();
217 Address ArgAddr = ArgLVal.getAddress();
218 if (!VarTy->isReferenceType()) {
219 ArgAddr = EmitLoadOfReference(
220 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
221 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000222 setAddrOfLocalVar(
223 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 } else if (I->capturesVariableByCopy()) {
225 assert(!FD->getType()->isAnyPointerType() &&
226 "Not expecting a captured pointer.");
227 auto *Var = I->getCapturedVar();
228 QualType VarTy = Var->getType();
229 setAddrOfLocalVar(I->getCapturedVar(),
230 castValueFromUintptr(*this, FD->getType(),
231 Args[Cnt]->getName(), ArgLVal,
232 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 } else {
234 // If 'this' is captured, load it into CXXThisValue.
235 assert(I->capturesThis());
236 CXXThisValue =
237 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
238 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000239 ++Cnt;
240 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241 }
242
Serge Pavlov3a561452015-12-06 14:32:39 +0000243 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 CapturedStmtInfo->EmitBody(*this, CD->getBody());
245 FinishFunction(CD->getBodyRBrace());
246
247 return F;
248}
249
Alexey Bataev9959db52014-05-06 10:08:46 +0000250//===----------------------------------------------------------------------===//
251// OpenMP Directive Emission
252//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000253void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address DestAddr, Address SrcAddr, QualType OriginalType,
255 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000256 // Perform element-by-element initialization.
257 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000258
259 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000261 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
262 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
263
264 auto SrcBegin = SrcAddr.getPointer();
265 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
268 // The basic structure here is a while-do loop.
269 auto BodyBB = createBasicBlock("omp.arraycpy.body");
270 auto DoneBB = createBasicBlock("omp.arraycpy.done");
271 auto IsEmpty =
272 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
273 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000274
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Enter the loop body, making that address the current address.
276 auto EntryBB = Builder.GetInsertBlock();
277 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000278
279 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
280
281 llvm::PHINode *SrcElementPHI =
282 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
283 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
284 Address SrcElementCurrent =
285 Address(SrcElementPHI,
286 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
287
288 llvm::PHINode *DestElementPHI =
289 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
290 DestElementPHI->addIncoming(DestBegin, EntryBB);
291 Address DestElementCurrent =
292 Address(DestElementPHI,
293 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000294
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Emit copy.
296 CopyGen(DestElementCurrent, SrcElementCurrent);
297
298 // Shift the address forward by one element.
299 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000300 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000302 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000303 // Check whether we've reached the end.
304 auto Done =
305 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
306 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000307 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
308 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000309
310 // Done.
311 EmitBlock(DoneBB, /*IsFinished=*/true);
312}
313
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000314/// Check if the combiner is a call to UDR combiner and if it is so return the
315/// UDR decl used for reduction.
316static const OMPDeclareReductionDecl *
317getReductionInit(const Expr *ReductionOp) {
318 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
319 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
320 if (auto *DRE =
321 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
322 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
323 return DRD;
324 return nullptr;
325}
326
327static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
328 const OMPDeclareReductionDecl *DRD,
329 const Expr *InitOp,
330 Address Private, Address Original,
331 QualType Ty) {
332 if (DRD->getInitializer()) {
333 std::pair<llvm::Function *, llvm::Function *> Reduction =
334 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
335 auto *CE = cast<CallExpr>(InitOp);
336 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
337 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
338 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
339 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
340 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
341 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
342 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
343 [=]() -> Address { return Private; });
344 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
345 [=]() -> Address { return Original; });
346 (void)PrivateScope.Privatize();
347 RValue Func = RValue::get(Reduction.second);
348 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
349 CGF.EmitIgnoredExpr(InitOp);
350 } else {
351 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
352 auto *GV = new llvm::GlobalVariable(
353 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
354 llvm::GlobalValue::PrivateLinkage, Init, ".init");
355 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
356 RValue InitRVal;
357 switch (CGF.getEvaluationKind(Ty)) {
358 case TEK_Scalar:
359 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
360 break;
361 case TEK_Complex:
362 InitRVal =
363 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
364 break;
365 case TEK_Aggregate:
366 InitRVal = RValue::getAggregate(LV.getAddress());
367 break;
368 }
369 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
370 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
371 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
372 /*IsInitializer=*/false);
373 }
374}
375
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000376/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000377/// \param DestAddr Address of the array.
378/// \param Type Type of array.
379/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000380/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000381static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000382 QualType Type, const Expr *Init,
383 Address SrcAddr = Address::invalid()) {
384 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000385 // Perform element-by-element initialization.
386 QualType ElementTy;
387
388 // Drill down to the base element type on both arrays.
389 auto ArrayTy = Type->getAsArrayTypeUnsafe();
390 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
391 DestAddr =
392 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000393 if (DRD)
394 SrcAddr =
395 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000396
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000397 llvm::Value *SrcBegin = nullptr;
398 if (DRD)
399 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000400 auto DestBegin = DestAddr.getPointer();
401 // Cast from pointer to array type to pointer to single element.
402 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
403 // The basic structure here is a while-do loop.
404 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
405 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
406 auto IsEmpty =
407 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
408 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
409
410 // Enter the loop body, making that address the current address.
411 auto EntryBB = CGF.Builder.GetInsertBlock();
412 CGF.EmitBlock(BodyBB);
413
414 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
415
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000416 llvm::PHINode *SrcElementPHI = nullptr;
417 Address SrcElementCurrent = Address::invalid();
418 if (DRD) {
419 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
420 "omp.arraycpy.srcElementPast");
421 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
422 SrcElementCurrent =
423 Address(SrcElementPHI,
424 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
425 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000426 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
427 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
428 DestElementPHI->addIncoming(DestBegin, EntryBB);
429 Address DestElementCurrent =
430 Address(DestElementPHI,
431 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
432
433 // Emit copy.
434 {
435 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000436 if (DRD) {
437 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
438 SrcElementCurrent, ElementTy);
439 } else
440 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
441 /*IsInitializer=*/false);
442 }
443
444 if (DRD) {
445 // Shift the address forward by one element.
446 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
447 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
448 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000449 }
450
451 // Shift the address forward by one element.
452 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
453 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
454 // Check whether we've reached the end.
455 auto Done =
456 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
457 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
458 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
459
460 // Done.
461 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
462}
463
John McCall7f416cc2015-09-08 08:05:57 +0000464void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
465 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000466 const VarDecl *SrcVD, const Expr *Copy) {
467 if (OriginalType->isArrayType()) {
468 auto *BO = dyn_cast<BinaryOperator>(Copy);
469 if (BO && BO->getOpcode() == BO_Assign) {
470 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000471 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000472 } else {
473 // For arrays with complex element types perform element by element
474 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000475 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000476 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000477 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000478 // Working with the single array element, so have to remap
479 // destination and source variables to corresponding array
480 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000481 CodeGenFunction::OMPPrivateScope Remap(*this);
482 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000483 return DestElement;
484 });
485 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000486 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000487 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000488 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000489 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000490 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000491 } else {
492 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000493 CodeGenFunction::OMPPrivateScope Remap(*this);
494 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
495 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000496 (void)Remap.Privatize();
497 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000498 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000499 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000500}
501
Alexey Bataev69c62a92015-04-15 04:52:20 +0000502bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
503 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000504 if (!HaveInsertPoint())
505 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000506 bool FirstprivateIsLastprivate = false;
507 llvm::DenseSet<const VarDecl *> Lastprivates;
508 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
509 for (const auto *D : C->varlists())
510 Lastprivates.insert(
511 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
512 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000513 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000514 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000515 auto IRef = C->varlist_begin();
516 auto InitsRef = C->inits().begin();
517 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000518 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000519 FirstprivateIsLastprivate =
520 FirstprivateIsLastprivate ||
521 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
522 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000523 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
524 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
525 bool IsRegistered;
526 DeclRefExpr DRE(
527 const_cast<VarDecl *>(OrigVD),
528 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
529 OrigVD) != nullptr,
530 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000532 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000533 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000534 // Emit VarDecl with copy init for arrays.
535 // Get the address of the original variable captured in current
536 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000537 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000538 auto Emission = EmitAutoVarAlloca(*VD);
539 auto *Init = VD->getInit();
540 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
541 // Perform simple memcpy.
542 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000543 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000544 } else {
545 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000546 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000547 [this, VDInit, Init](Address DestElement,
548 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000549 // Clean up any temporaries needed by the initialization.
550 RunCleanupsScope InitScope(*this);
551 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000552 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000553 EmitAnyExprToMem(Init, DestElement,
554 Init->getType().getQualifiers(),
555 /*IsInitializer*/ false);
556 LocalDeclMap.erase(VDInit);
557 });
558 }
559 EmitAutoVarCleanups(Emission);
560 return Emission.getAllocatedAddress();
561 });
562 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000563 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000564 // Emit private VarDecl with copy init.
565 // Remap temp VDInit variable to the address of the original
566 // variable
567 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000568 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000569 EmitDecl(*VD);
570 LocalDeclMap.erase(VDInit);
571 return GetAddrOfLocalVar(VD);
572 });
573 }
574 assert(IsRegistered &&
575 "firstprivate var already registered as private");
576 // Silence the warning about unused variable.
577 (void)IsRegistered;
578 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000579 ++IRef;
580 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000581 }
582 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000583 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000584}
585
Alexey Bataev03b340a2014-10-21 03:16:40 +0000586void CodeGenFunction::EmitOMPPrivateClause(
587 const OMPExecutableDirective &D,
588 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000591 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000592 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000593 auto IRef = C->varlist_begin();
594 for (auto IInit : C->private_copies()) {
595 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000596 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
597 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
598 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000599 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000600 // Emit private VarDecl with copy init.
601 EmitDecl(*VD);
602 return GetAddrOfLocalVar(VD);
603 });
604 assert(IsRegistered && "private var already registered as private");
605 // Silence the warning about unused variable.
606 (void)IsRegistered;
607 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000608 ++IRef;
609 }
610 }
611}
612
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000613bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000614 if (!HaveInsertPoint())
615 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000616 // threadprivate_var1 = master_threadprivate_var1;
617 // operator=(threadprivate_var2, master_threadprivate_var2);
618 // ...
619 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000620 llvm::DenseSet<const VarDecl *> CopiedVars;
621 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000622 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000623 auto IRef = C->varlist_begin();
624 auto ISrcRef = C->source_exprs().begin();
625 auto IDestRef = C->destination_exprs().begin();
626 for (auto *AssignOp : C->assignment_ops()) {
627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000628 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000629 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000630 // Get the address of the master variable. If we are emitting code with
631 // TLS support, the address is passed from the master as field in the
632 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000634 if (getLangOpts().OpenMPUseTLS &&
635 getContext().getTargetInfo().isTLSSupported()) {
636 assert(CapturedStmtInfo->lookup(VD) &&
637 "Copyin threadprivates should have been captured!");
638 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
639 VK_LValue, (*IRef)->getExprLoc());
640 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000641 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000642 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000643 MasterAddr =
644 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
645 : CGM.GetAddrOfGlobal(VD),
646 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000647 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000648 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000649 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000650 if (CopiedVars.size() == 1) {
651 // At first check if current thread is a master thread. If it is, no
652 // need to copy data.
653 CopyBegin = createBasicBlock("copyin.not.master");
654 CopyEnd = createBasicBlock("copyin.not.master.end");
655 Builder.CreateCondBr(
656 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000657 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
658 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000659 CopyBegin, CopyEnd);
660 EmitBlock(CopyBegin);
661 }
662 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
663 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000664 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000665 }
666 ++IRef;
667 ++ISrcRef;
668 ++IDestRef;
669 }
670 }
671 if (CopyEnd) {
672 // Exit out of copying procedure for non-master thread.
673 EmitBlock(CopyEnd, /*IsFinished=*/true);
674 return true;
675 }
676 return false;
677}
678
Alexey Bataev38e89532015-04-16 04:54:05 +0000679bool CodeGenFunction::EmitOMPLastprivateClauseInit(
680 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000681 if (!HaveInsertPoint())
682 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000683 bool HasAtLeastOneLastprivate = false;
684 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000685 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000686 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 auto IRef = C->varlist_begin();
688 auto IDestRef = C->destination_exprs().begin();
689 for (auto *IInit : C->private_copies()) {
690 // Keep the address of the original variable for future update at the end
691 // of the loop.
692 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
693 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
694 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000695 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000696 DeclRefExpr DRE(
697 const_cast<VarDecl *>(OrigVD),
698 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
699 OrigVD) != nullptr,
700 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
701 return EmitLValue(&DRE).getAddress();
702 });
703 // Check if the variable is also a firstprivate: in this case IInit is
704 // not generated. Initialization of this variable will happen in codegen
705 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000706 if (IInit) {
707 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
708 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000709 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000710 // Emit private VarDecl with copy init.
711 EmitDecl(*VD);
712 return GetAddrOfLocalVar(VD);
713 });
714 assert(IsRegistered &&
715 "lastprivate var already registered as private");
716 (void)IsRegistered;
717 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000718 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000719 ++IRef;
720 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000721 }
722 }
723 return HasAtLeastOneLastprivate;
724}
725
726void CodeGenFunction::EmitOMPLastprivateClauseFinal(
727 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000728 if (!HaveInsertPoint())
729 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000730 // Emit following code:
731 // if (<IsLastIterCond>) {
732 // orig_var1 = private_orig_var1;
733 // ...
734 // orig_varn = private_orig_varn;
735 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000736 llvm::BasicBlock *ThenBB = nullptr;
737 llvm::BasicBlock *DoneBB = nullptr;
738 if (IsLastIterCond) {
739 ThenBB = createBasicBlock(".omp.lastprivate.then");
740 DoneBB = createBasicBlock(".omp.lastprivate.done");
741 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
742 EmitBlock(ThenBB);
743 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000744 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000745 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000746 auto IC = LoopDirective->counters().begin();
747 for (auto F : LoopDirective->finals()) {
748 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
749 LoopCountersAndUpdates[D] = F;
750 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000751 }
752 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000753 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
754 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
755 auto IRef = C->varlist_begin();
756 auto ISrcRef = C->source_exprs().begin();
757 auto IDestRef = C->destination_exprs().begin();
758 for (auto *AssignOp : C->assignment_ops()) {
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
760 QualType Type = PrivateVD->getType();
761 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
762 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
763 // If lastprivate variable is a loop control variable for loop-based
764 // directive, update its value before copyin back to original
765 // variable.
766 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
767 EmitIgnoredExpr(UpExpr);
768 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
769 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
770 // Get the address of the original variable.
771 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
772 // Get the address of the private variable.
773 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
774 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
775 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000776 Address(Builder.CreateLoad(PrivateAddr),
777 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000778 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000779 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000780 ++IRef;
781 ++ISrcRef;
782 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000783 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000784 if (auto *PostUpdate = C->getPostUpdateExpr())
785 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000786 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000787 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000788 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000789}
790
Alexey Bataev31300ed2016-02-04 11:27:03 +0000791static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
792 LValue BaseLV, llvm::Value *Addr) {
793 Address Tmp = Address::invalid();
794 Address TopTmp = Address::invalid();
795 Address MostTopTmp = Address::invalid();
796 BaseTy = BaseTy.getNonReferenceType();
797 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
798 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
799 Tmp = CGF.CreateMemTemp(BaseTy);
800 if (TopTmp.isValid())
801 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
802 else
803 MostTopTmp = Tmp;
804 TopTmp = Tmp;
805 BaseTy = BaseTy->getPointeeType();
806 }
807 llvm::Type *Ty = BaseLV.getPointer()->getType();
808 if (Tmp.isValid())
809 Ty = Tmp.getElementType();
810 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
811 if (Tmp.isValid()) {
812 CGF.Builder.CreateStore(Addr, Tmp);
813 return MostTopTmp;
814 }
815 return Address(Addr, BaseLV.getAlignment());
816}
817
818static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
819 LValue BaseLV) {
820 BaseTy = BaseTy.getNonReferenceType();
821 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
822 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
823 if (auto *PtrTy = BaseTy->getAs<PointerType>())
824 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
825 else {
826 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
827 BaseTy->castAs<ReferenceType>());
828 }
829 BaseTy = BaseTy->getPointeeType();
830 }
831 return CGF.MakeAddrLValue(
832 Address(
833 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
834 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
835 BaseLV.getAlignment()),
836 BaseLV.getType(), BaseLV.getAlignmentSource());
837}
838
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000839void CodeGenFunction::EmitOMPReductionClauseInit(
840 const OMPExecutableDirective &D,
841 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000842 if (!HaveInsertPoint())
843 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000844 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000845 auto ILHS = C->lhs_exprs().begin();
846 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000847 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000848 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000849 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000850 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000851 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
852 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000853 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000854 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
855 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
856 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
857 Base = TempOASE->getBase()->IgnoreParenImpCasts();
858 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
859 Base = TempASE->getBase()->IgnoreParenImpCasts();
860 auto *DE = cast<DeclRefExpr>(Base);
861 auto *OrigVD = cast<VarDecl>(DE->getDecl());
862 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
863 auto OASELValueUB =
864 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
865 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000866 LValue BaseLValue =
867 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
868 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000869 // Store the address of the original variable associated with the LHS
870 // implicit variable.
871 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
872 return OASELValueLB.getAddress();
873 });
874 // Emit reduction copy.
875 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000876 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000877 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000878 // Emit VarDecl with copy init for arrays.
879 // Get the address of the original variable captured in current
880 // captured region.
881 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
882 OASELValueLB.getPointer());
883 Size = Builder.CreateNUWAdd(
884 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
885 CodeGenFunction::OpaqueValueMapping OpaqueMap(
886 *this, cast<OpaqueValueExpr>(
887 getContext()
888 .getAsVariableArrayType(PrivateVD->getType())
889 ->getSizeExpr()),
890 RValue::get(Size));
891 EmitVariablyModifiedType(PrivateVD->getType());
892 auto Emission = EmitAutoVarAlloca(*PrivateVD);
893 auto Addr = Emission.getAllocatedAddress();
894 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000895 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
896 DRD ? *IRed : Init,
897 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000898 EmitAutoVarCleanups(Emission);
899 // Emit private VarDecl with reduction init.
900 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
901 OASELValueLB.getPointer());
902 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000903 return castToBase(*this, OrigVD->getType(),
904 OASELValueLB.getType(), OriginalBaseLValue,
905 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000906 });
907 assert(IsRegistered && "private var already registered as private");
908 // Silence the warning about unused variable.
909 (void)IsRegistered;
910 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
911 return GetAddrOfLocalVar(PrivateVD);
912 });
913 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
914 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
915 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
916 Base = TempASE->getBase()->IgnoreParenImpCasts();
917 auto *DE = cast<DeclRefExpr>(Base);
918 auto *OrigVD = cast<VarDecl>(DE->getDecl());
919 auto ASELValue = EmitLValue(ASE);
920 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000921 LValue BaseLValue = loadToBegin(
922 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000923 // Store the address of the original variable associated with the LHS
924 // implicit variable.
925 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
926 return ASELValue.getAddress();
927 });
928 // Emit reduction copy.
929 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000930 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000931 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000932 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000933 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
934 auto Addr = Emission.getAllocatedAddress();
935 if (DRD) {
936 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
937 ASELValue.getAddress(),
938 ASELValue.getType());
939 } else
940 EmitAutoVarInit(Emission);
941 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
943 ASELValue.getPointer());
944 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000945 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
946 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000947 });
948 assert(IsRegistered && "private var already registered as private");
949 // Silence the warning about unused variable.
950 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000951 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
952 return Builder.CreateElementBitCast(
953 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
954 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000955 });
956 } else {
957 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000958 QualType Type = PrivateVD->getType();
959 if (getContext().getAsArrayType(Type)) {
960 // Store the address of the original variable associated with the LHS
961 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000962 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
963 CapturedStmtInfo->lookup(OrigVD) != nullptr,
964 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000965 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000966 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +0000967 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000968 OriginalAddr = Builder.CreateElementBitCast(
969 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
970 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000971 });
972 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
973 if (Type->isVariablyModifiedType()) {
974 CodeGenFunction::OpaqueValueMapping OpaqueMap(
975 *this, cast<OpaqueValueExpr>(
976 getContext()
977 .getAsVariableArrayType(PrivateVD->getType())
978 ->getSizeExpr()),
979 RValue::get(
980 getTypeSize(OrigVD->getType().getNonReferenceType())));
981 EmitVariablyModifiedType(Type);
982 }
983 auto Emission = EmitAutoVarAlloca(*PrivateVD);
984 auto Addr = Emission.getAllocatedAddress();
985 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000986 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
987 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000988 EmitAutoVarCleanups(Emission);
989 return Emission.getAllocatedAddress();
990 });
991 assert(IsRegistered && "private var already registered as private");
992 // Silence the warning about unused variable.
993 (void)IsRegistered;
994 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
995 return Builder.CreateElementBitCast(
996 GetAddrOfLocalVar(PrivateVD),
997 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
998 });
999 } else {
1000 // Store the address of the original variable associated with the LHS
1001 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001002 Address OriginalAddr = Address::invalid();
1003 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1004 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001005 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1006 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1007 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001008 OriginalAddr = EmitLValue(&DRE).getAddress();
1009 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001010 });
1011 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001012 bool IsRegistered = PrivateScope.addPrivate(
1013 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001014 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001015 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1016 auto Addr = Emission.getAllocatedAddress();
1017 if (DRD) {
1018 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1019 OriginalAddr,
1020 PrivateVD->getType());
1021 } else
1022 EmitAutoVarInit(Emission);
1023 EmitAutoVarCleanups(Emission);
1024 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001025 });
1026 assert(IsRegistered && "private var already registered as private");
1027 // Silence the warning about unused variable.
1028 (void)IsRegistered;
1029 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1030 return GetAddrOfLocalVar(PrivateVD);
1031 });
1032 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001033 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001034 ++ILHS;
1035 ++IRHS;
1036 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001037 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001038 }
1039 }
1040}
1041
1042void CodeGenFunction::EmitOMPReductionClauseFinal(
1043 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001044 if (!HaveInsertPoint())
1045 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001046 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001047 llvm::SmallVector<const Expr *, 8> LHSExprs;
1048 llvm::SmallVector<const Expr *, 8> RHSExprs;
1049 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001050 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001051 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001052 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001053 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001054 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1055 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1056 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1057 }
1058 if (HasAtLeastOneReduction) {
1059 // Emit nowait reduction if nowait clause is present or directive is a
1060 // parallel directive (it always has implicit barrier).
1061 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001062 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001063 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001064 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1065 D.getDirectiveKind() == OMPD_simd,
1066 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001067 }
1068}
1069
Alexey Bataev61205072016-03-02 04:57:40 +00001070static void emitPostUpdateForReductionClause(
1071 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1072 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1073 if (!CGF.HaveInsertPoint())
1074 return;
1075 llvm::BasicBlock *DoneBB = nullptr;
1076 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1077 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1078 if (!DoneBB) {
1079 if (auto *Cond = CondGen(CGF)) {
1080 // If the first post-update expression is found, emit conditional
1081 // block if it was requested.
1082 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1083 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1084 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1085 CGF.EmitBlock(ThenBB);
1086 }
1087 }
1088 CGF.EmitIgnoredExpr(PostUpdate);
1089 }
1090 }
1091 if (DoneBB)
1092 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1093}
1094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001095static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1096 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001097 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001098 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001099 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001100 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1101 emitParallelOrTeamsOutlinedFunction(S,
1102 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001103 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001104 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001105 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1106 /*IgnoreResultAssign*/ true);
1107 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1108 CGF, NumThreads, NumThreadsClause->getLocStart());
1109 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001110 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001111 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001112 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1113 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1114 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001115 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001116 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1117 if (C->getNameModifier() == OMPD_unknown ||
1118 C->getNameModifier() == OMPD_parallel) {
1119 IfCond = C->getCondition();
1120 break;
1121 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001122 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001123
1124 OMPLexicalScope Scope(CGF, S);
1125 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1126 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001127 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001128 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001129}
1130
1131void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001132 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001133 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001135 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001136 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1137 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001138 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001139 // propagation master's thread values of threadprivate variables to local
1140 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001141 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1142 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1143 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001144 }
1145 CGF.EmitOMPPrivateClause(S, PrivateScope);
1146 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1147 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001148 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001149 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001150 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001151 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001152 emitPostUpdateForReductionClause(
1153 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001154}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001155
Alexey Bataev0f34da12015-07-02 04:17:07 +00001156void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1157 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001158 RunCleanupsScope BodyScope(*this);
1159 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001160 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001161 EmitIgnoredExpr(I);
1162 }
Alexander Musman3276a272015-03-21 10:12:56 +00001163 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001164 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001165 for (auto U : C->updates()) {
1166 EmitIgnoredExpr(U);
1167 }
1168 }
1169
Alexander Musmana5f070a2014-10-01 06:03:56 +00001170 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001171 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001172 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001173 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001174 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001175 // The end (updates/cleanups).
1176 EmitBlock(Continue.getBlock());
1177 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001178}
1179
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180void CodeGenFunction::EmitOMPInnerLoop(
1181 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1182 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001183 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1184 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001185 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001186
1187 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001188 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001189 EmitBlock(CondBlock);
1190 LoopStack.push(CondBlock);
1191
1192 // If there are any cleanups between here and the loop-exit scope,
1193 // create a block to stage a loop exit along.
1194 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001195 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001196 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001197
Alexander Musmand196ef22014-10-07 08:57:09 +00001198 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001199
Alexey Bataev2df54a02015-03-12 08:53:29 +00001200 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001201 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001202 if (ExitBlock != LoopExit.getBlock()) {
1203 EmitBlock(ExitBlock);
1204 EmitBranchThroughCleanup(LoopExit);
1205 }
1206
1207 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001208 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001209
1210 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001211 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001212 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1213
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001214 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001215
1216 // Emit "IV = IV + 1" and a back-edge to the condition block.
1217 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001218 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001219 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001220 BreakContinueStack.pop_back();
1221 EmitBranch(CondBlock);
1222 LoopStack.pop();
1223 // Emit the fall-through block.
1224 EmitBlock(LoopExit.getBlock());
1225}
1226
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001227void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001228 if (!HaveInsertPoint())
1229 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001230 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001231 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001232 for (auto Init : C->inits()) {
1233 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001234 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1235 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1236 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1237 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1238 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1239 VD->getInit()->getType(), VK_LValue,
1240 VD->getInit()->getExprLoc());
1241 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1242 VD->getType()),
1243 /*capturedByInit=*/false);
1244 EmitAutoVarCleanups(Emission);
1245 } else
1246 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001247 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001248 // Emit the linear steps for the linear clauses.
1249 // If a step is not constant, it is pre-calculated before the loop.
1250 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1251 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001252 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001253 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001254 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001255 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001256 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001257}
1258
Alexey Bataevef549a82016-03-09 09:49:09 +00001259static void emitLinearClauseFinal(
1260 CodeGenFunction &CGF, const OMPLoopDirective &D,
1261 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001262 if (!CGF.HaveInsertPoint())
1263 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001264 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001265 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001266 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001267 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001268 for (auto F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001269 if (!DoneBB) {
1270 if (auto *Cond = CondGen(CGF)) {
1271 // If the first post-update expression is found, emit conditional
1272 // block if it was requested.
1273 auto *ThenBB = CGF.createBasicBlock(".omp.linear.pu");
1274 DoneBB = CGF.createBasicBlock(".omp.linear.pu.done");
1275 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1276 CGF.EmitBlock(ThenBB);
1277 }
1278 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001279 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1280 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001281 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001282 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001283 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001284 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001285 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001286 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001287 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001288 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001289 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001290 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001291 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataevef549a82016-03-09 09:49:09 +00001292 CGF.EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001293 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001294 if (DoneBB)
1295 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001296}
1297
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001298static void emitAlignedClause(CodeGenFunction &CGF,
1299 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001300 if (!CGF.HaveInsertPoint())
1301 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001302 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001303 unsigned ClauseAlignment = 0;
1304 if (auto AlignmentExpr = Clause->getAlignment()) {
1305 auto AlignmentCI =
1306 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1307 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001308 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001309 for (auto E : Clause->varlists()) {
1310 unsigned Alignment = ClauseAlignment;
1311 if (Alignment == 0) {
1312 // OpenMP [2.8.1, Description]
1313 // If no optional parameter is specified, implementation-defined default
1314 // alignments for SIMD instructions on the target platforms are assumed.
1315 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001316 CGF.getContext()
1317 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1318 E->getType()->getPointeeType()))
1319 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001320 }
1321 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1322 "alignment is not power of 2");
1323 if (Alignment != 0) {
1324 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1325 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1326 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001327 }
1328 }
1329}
1330
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001331static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001332 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001333 ArrayRef<Expr *> Counters,
1334 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001335 if (!CGF.HaveInsertPoint())
1336 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001337 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001338 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001339 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1340 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001341 Address Addr = Address::invalid();
1342 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001343 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001344 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001345 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001346 Addr = VarEmission.getAllocatedAddress();
1347 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001348 });
John McCall7f416cc2015-09-08 08:05:57 +00001349 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001350 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001351 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001352}
1353
Alexey Bataev62dbb972015-04-22 11:59:37 +00001354static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1355 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1356 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001357 if (!CGF.HaveInsertPoint())
1358 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001359 {
1360 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001361 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1362 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001363 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001364 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001365 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001366 CGF.EmitIgnoredExpr(I);
1367 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001368 }
1369 // Check that loop is executed at least one time.
1370 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1371}
1372
Alexander Musman3276a272015-03-21 10:12:56 +00001373static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001374emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001375 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001376 if (!CGF.HaveInsertPoint())
1377 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001378 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001379 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001380 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001381 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1382 auto *PrivateVD =
1383 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001384 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001385 // Emit private VarDecl with copy init.
1386 CGF.EmitVarDecl(*PrivateVD);
1387 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001388 });
1389 assert(IsRegistered && "linear var already registered as private");
1390 // Silence the warning about unused variable.
1391 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001392 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001393 }
1394 }
1395}
1396
Alexey Bataev45bfad52015-08-21 12:19:04 +00001397static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001398 const OMPExecutableDirective &D,
1399 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001400 if (!CGF.HaveInsertPoint())
1401 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001402 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001403 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1404 /*ignoreResult=*/true);
1405 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1406 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1407 // In presence of finite 'safelen', it may be unsafe to mark all
1408 // the memory instructions parallel, because loop-carried
1409 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001410 if (!IsMonotonic)
1411 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001412 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001413 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1414 /*ignoreResult=*/true);
1415 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001416 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001417 // In presence of finite 'safelen', it may be unsafe to mark all
1418 // the memory instructions parallel, because loop-carried
1419 // dependences of 'safelen' iterations are possible.
1420 CGF.LoopStack.setParallel(false);
1421 }
1422}
1423
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001424void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1425 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001426 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001427 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001428 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001429 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001430}
1431
Alexey Bataevef549a82016-03-09 09:49:09 +00001432void CodeGenFunction::EmitOMPSimdFinal(
1433 const OMPLoopDirective &D,
1434 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001435 if (!HaveInsertPoint())
1436 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001437 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001438 auto IC = D.counters().begin();
1439 for (auto F : D.finals()) {
1440 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001441 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001442 if (!DoneBB) {
1443 if (auto *Cond = CondGen(*this)) {
1444 // If the first post-update expression is found, emit conditional
1445 // block if it was requested.
1446 auto *ThenBB = createBasicBlock(".omp.final.then");
1447 DoneBB = createBasicBlock(".omp.final.done");
1448 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1449 EmitBlock(ThenBB);
1450 }
1451 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001452 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1453 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1454 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001455 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001456 OMPPrivateScope VarScope(*this);
1457 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001458 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001459 (void)VarScope.Privatize();
1460 EmitIgnoredExpr(F);
1461 }
1462 ++IC;
1463 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001464 if (DoneBB)
1465 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001466}
1467
Alexander Musman515ad8c2014-05-22 08:54:05 +00001468void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001469 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001470 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001471 // for (IV in 0..LastIteration) BODY;
1472 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001473 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001474 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001475
Alexey Bataev62dbb972015-04-22 11:59:37 +00001476 // Emit: if (PreCond) - begin.
1477 // If the condition constant folds and can be elided, avoid emitting the
1478 // whole loop.
1479 bool CondConstant;
1480 llvm::BasicBlock *ContBlock = nullptr;
1481 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1482 if (!CondConstant)
1483 return;
1484 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001485 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1486 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001487 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1488 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001489 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001490 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001491 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001492
1493 // Emit the loop iteration variable.
1494 const Expr *IVExpr = S.getIterationVariable();
1495 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1496 CGF.EmitVarDecl(*IVDecl);
1497 CGF.EmitIgnoredExpr(S.getInit());
1498
1499 // Emit the iterations count variable.
1500 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001501 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001502 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1503 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1504 // Emit calculation of the iterations count.
1505 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001506 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001507
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001508 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001509
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001510 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001511 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001512 {
1513 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001514 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1515 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001516 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001517 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001518 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001519 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001520 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001521 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1522 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001523 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001524 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001525 CGF.EmitStopPoint(&S);
1526 },
1527 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001528 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001529 if (HasLastprivateClause)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001530 CGF.EmitOMPLastprivateClauseFinal(S);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001531 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001532 emitPostUpdateForReductionClause(
1533 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001534 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001535 CGF.EmitOMPSimdFinal(
1536 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1537 emitLinearClauseFinal(
1538 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001539 // Emit: if (PreCond) - end.
1540 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001541 CGF.EmitBranch(ContBlock);
1542 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001543 }
1544 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001545 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001546 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001547}
1548
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001549void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001550 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1551 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001552 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001553
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001554 const Expr *IVExpr = S.getIterationVariable();
1555 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1556 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1557
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001558 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1559
1560 // Start the loop with a block that tests the condition.
1561 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1562 EmitBlock(CondBlock);
1563 LoopStack.push(CondBlock);
1564
1565 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001566 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001567 // UB = min(UB, GlobalUB)
1568 EmitIgnoredExpr(S.getEnsureUpperBound());
1569 // IV = LB
1570 EmitIgnoredExpr(S.getInit());
1571 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001572 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001573 } else {
1574 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1575 IL, LB, UB, ST);
1576 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001577
1578 // If there are any cleanups between here and the loop-exit scope,
1579 // create a block to stage a loop exit along.
1580 auto ExitBlock = LoopExit.getBlock();
1581 if (LoopScope.requiresCleanups())
1582 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1583
1584 auto LoopBody = createBasicBlock("omp.dispatch.body");
1585 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1586 if (ExitBlock != LoopExit.getBlock()) {
1587 EmitBlock(ExitBlock);
1588 EmitBranchThroughCleanup(LoopExit);
1589 }
1590 EmitBlock(LoopBody);
1591
Alexander Musman92bdaab2015-03-12 13:37:50 +00001592 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1593 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001594 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001595 EmitIgnoredExpr(S.getInit());
1596
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001597 // Create a block for the increment.
1598 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1599 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1600
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001601 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1602 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001603 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1604 LoopStack.setParallel(!IsMonotonic);
1605 else
1606 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001607
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001608 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001609 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1610 [&S, LoopExit](CodeGenFunction &CGF) {
1611 CGF.EmitOMPLoopBody(S, LoopExit);
1612 CGF.EmitStopPoint(&S);
1613 },
1614 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1615 if (Ordered) {
1616 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1617 CGF, Loc, IVSize, IVSigned);
1618 }
1619 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001620
1621 EmitBlock(Continue.getBlock());
1622 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001623 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001624 // Emit "LB = LB + Stride", "UB = UB + Stride".
1625 EmitIgnoredExpr(S.getNextLowerBound());
1626 EmitIgnoredExpr(S.getNextUpperBound());
1627 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001628
1629 EmitBranch(CondBlock);
1630 LoopStack.pop();
1631 // Emit the fall-through block.
1632 EmitBlock(LoopExit.getBlock());
1633
1634 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001635 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001636 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001637
1638}
1639
1640void CodeGenFunction::EmitOMPForOuterLoop(
1641 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1642 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1643 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1644 auto &RT = CGM.getOpenMPRuntime();
1645
1646 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1647 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1648
1649 assert((Ordered ||
1650 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1651 "static non-chunked schedule does not need outer loop");
1652
1653 // Emit outer loop.
1654 //
1655 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1656 // When schedule(dynamic,chunk_size) is specified, the iterations are
1657 // distributed to threads in the team in chunks as the threads request them.
1658 // Each thread executes a chunk of iterations, then requests another chunk,
1659 // until no chunks remain to be distributed. Each chunk contains chunk_size
1660 // iterations, except for the last chunk to be distributed, which may have
1661 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1662 //
1663 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1664 // to threads in the team in chunks as the executing threads request them.
1665 // Each thread executes a chunk of iterations, then requests another chunk,
1666 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1667 // each chunk is proportional to the number of unassigned iterations divided
1668 // by the number of threads in the team, decreasing to 1. For a chunk_size
1669 // with value k (greater than 1), the size of each chunk is determined in the
1670 // same way, with the restriction that the chunks do not contain fewer than k
1671 // iterations (except for the last chunk to be assigned, which may have fewer
1672 // than k iterations).
1673 //
1674 // When schedule(auto) is specified, the decision regarding scheduling is
1675 // delegated to the compiler and/or runtime system. The programmer gives the
1676 // implementation the freedom to choose any possible mapping of iterations to
1677 // threads in the team.
1678 //
1679 // When schedule(runtime) is specified, the decision regarding scheduling is
1680 // deferred until run time, and the schedule and chunk size are taken from the
1681 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1682 // implementation defined
1683 //
1684 // while(__kmpc_dispatch_next(&LB, &UB)) {
1685 // idx = LB;
1686 // while (idx <= UB) { BODY; ++idx;
1687 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1688 // } // inner loop
1689 // }
1690 //
1691 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1692 // When schedule(static, chunk_size) is specified, iterations are divided into
1693 // chunks of size chunk_size, and the chunks are assigned to the threads in
1694 // the team in a round-robin fashion in the order of the thread number.
1695 //
1696 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1697 // while (idx <= UB) { BODY; ++idx; } // inner loop
1698 // LB = LB + ST;
1699 // UB = UB + ST;
1700 // }
1701 //
1702
1703 const Expr *IVExpr = S.getIterationVariable();
1704 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1705 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1706
1707 if (DynamicOrOrdered) {
1708 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1709 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1710 IVSize, IVSigned, Ordered, UBVal, Chunk);
1711 } else {
1712 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1713 Ordered, IL, LB, UB, ST, Chunk);
1714 }
1715
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001716 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001717 ST, IL, Chunk);
1718}
1719
1720void CodeGenFunction::EmitOMPDistributeOuterLoop(
1721 OpenMPDistScheduleClauseKind ScheduleKind,
1722 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1723 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1724
1725 auto &RT = CGM.getOpenMPRuntime();
1726
1727 // Emit outer loop.
1728 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1729 // dynamic
1730 //
1731
1732 const Expr *IVExpr = S.getIterationVariable();
1733 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1734 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1735
1736 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1737 IVSize, IVSigned, /* Ordered = */ false,
1738 IL, LB, UB, ST, Chunk);
1739
1740 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1741 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001742}
1743
Alexander Musmanc6388682014-12-15 07:07:06 +00001744/// \brief Emit a helper variable and return corresponding lvalue.
1745static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1746 const DeclRefExpr *Helper) {
1747 auto VDecl = cast<VarDecl>(Helper->getDecl());
1748 CGF.EmitVarDecl(*VDecl);
1749 return CGF.EmitLValue(Helper);
1750}
1751
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001752namespace {
1753 struct ScheduleKindModifiersTy {
1754 OpenMPScheduleClauseKind Kind;
1755 OpenMPScheduleClauseModifier M1;
1756 OpenMPScheduleClauseModifier M2;
1757 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1758 OpenMPScheduleClauseModifier M1,
1759 OpenMPScheduleClauseModifier M2)
1760 : Kind(Kind), M1(M1), M2(M2) {}
1761 };
1762} // namespace
1763
Alexey Bataev38e89532015-04-16 04:54:05 +00001764bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001765 // Emit the loop iteration variable.
1766 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1767 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1768 EmitVarDecl(*IVDecl);
1769
1770 // Emit the iterations count variable.
1771 // If it is not a variable, Sema decided to calculate iterations count on each
1772 // iteration (e.g., it is foldable into a constant).
1773 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1774 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1775 // Emit calculation of the iterations count.
1776 EmitIgnoredExpr(S.getCalcLastIteration());
1777 }
1778
1779 auto &RT = CGM.getOpenMPRuntime();
1780
Alexey Bataev38e89532015-04-16 04:54:05 +00001781 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001782 // Check pre-condition.
1783 {
1784 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001785 // If the condition constant folds and can be elided, avoid emitting the
1786 // whole loop.
1787 bool CondConstant;
1788 llvm::BasicBlock *ContBlock = nullptr;
1789 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1790 if (!CondConstant)
1791 return false;
1792 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001793 auto *ThenBlock = createBasicBlock("omp.precond.then");
1794 ContBlock = createBasicBlock("omp.precond.end");
1795 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001796 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001797 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001798 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001799 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001800
1801 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001802 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001803 // Emit helper vars inits.
1804 LValue LB =
1805 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1806 LValue UB =
1807 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1808 LValue ST =
1809 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1810 LValue IL =
1811 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1812
Alexander Musmanc6388682014-12-15 07:07:06 +00001813 // Emit 'then' code.
1814 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001815 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001816 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1817 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001818 // initialization of firstprivate variables and post-update of
1819 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001820 CGM.getOpenMPRuntime().emitBarrierCall(
1821 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1822 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001823 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001824 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001825 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001826 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001827 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1828 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001829 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001830 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001831
1832 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001833 llvm::Value *Chunk = nullptr;
1834 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1835 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1836 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1837 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1838 ScheduleKind = C->getScheduleKind();
1839 M1 = C->getFirstScheduleModifier();
1840 M2 = C->getSecondScheduleModifier();
1841 if (const auto *Ch = C->getChunkSize()) {
1842 Chunk = EmitScalarExpr(Ch);
1843 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1844 S.getIterationVariable()->getType(),
1845 S.getLocStart());
1846 }
1847 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001848 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1849 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001850 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001851 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1852 // If the static schedule kind is specified or if the ordered clause is
1853 // specified, and if no monotonic modifier is specified, the effect will
1854 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001855 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001856 /* Chunked */ Chunk != nullptr) &&
1857 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001858 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1859 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001860 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1861 // When no chunk_size is specified, the iteration space is divided into
1862 // chunks that are approximately equal in size, and at most one chunk is
1863 // distributed to each thread. Note that the size of the chunks is
1864 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001865 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1866 IVSize, IVSigned, Ordered,
1867 IL.getAddress(), LB.getAddress(),
1868 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001869 auto LoopExit =
1870 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001871 // UB = min(UB, GlobalUB);
1872 EmitIgnoredExpr(S.getEnsureUpperBound());
1873 // IV = LB;
1874 EmitIgnoredExpr(S.getInit());
1875 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001876 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1877 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001878 [&S, LoopExit](CodeGenFunction &CGF) {
1879 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001880 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001881 },
1882 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001883 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001884 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001885 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001886 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001887 const bool IsMonotonic = Ordered ||
1888 ScheduleKind == OMPC_SCHEDULE_static ||
1889 ScheduleKind == OMPC_SCHEDULE_unknown ||
1890 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1891 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001892 // Emit the outer loop, which requests its work chunk [LB..UB] from
1893 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001894 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001895 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1896 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001897 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001898 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001899 // Emit post-update of the reduction variables if IsLastIter != 0.
1900 emitPostUpdateForReductionClause(
1901 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1902 return CGF.Builder.CreateIsNotNull(
1903 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1904 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001905 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1906 if (HasLastprivateClause)
1907 EmitOMPLastprivateClauseFinal(
1908 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001909 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001910 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001911 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1912 return CGF.Builder.CreateIsNotNull(
1913 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1914 });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001915 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001916 emitLinearClauseFinal(*this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1917 return CGF.Builder.CreateIsNotNull(
1918 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1919 });
Alexander Musmanc6388682014-12-15 07:07:06 +00001920 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001921 if (ContBlock) {
1922 EmitBranch(ContBlock);
1923 EmitBlock(ContBlock, true);
1924 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001925 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001926 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001927}
1928
1929void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001930 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001931 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
1932 PrePostActionTy &) {
1933 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1934 };
Alexey Bataev3392d762016-02-16 11:18:12 +00001935 {
1936 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00001937 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1938 S.hasCancel());
1939 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001940
1941 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001942 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001943 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1944 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001945}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001946
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001947void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001948 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001949 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
1950 PrePostActionTy &) {
1951 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1952 };
Alexey Bataev3392d762016-02-16 11:18:12 +00001953 {
1954 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00001955 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1956 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001957
1958 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001959 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001960 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1961 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001962}
1963
Alexey Bataev2df54a02015-03-12 08:53:29 +00001964static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1965 const Twine &Name,
1966 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001967 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001968 if (Init)
1969 CGF.EmitScalarInit(Init, LVal);
1970 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001971}
1972
Alexey Bataev3392d762016-02-16 11:18:12 +00001973void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001974 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1975 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001976 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001977 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
1978 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001979 auto &C = CGF.CGM.getContext();
1980 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1981 // Emit helper vars inits.
1982 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1983 CGF.Builder.getInt32(0));
1984 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1985 : CGF.Builder.getInt32(0);
1986 LValue UB =
1987 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1988 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1989 CGF.Builder.getInt32(1));
1990 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1991 CGF.Builder.getInt32(0));
1992 // Loop counter.
1993 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1994 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1995 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1996 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1997 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1998 // Generate condition for loop.
1999 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2000 OK_Ordinary, S.getLocStart(),
2001 /*fpContractable=*/false);
2002 // Increment for loop counter.
2003 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2004 S.getLocStart());
2005 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2006 // Iterate through all sections and emit a switch construct:
2007 // switch (IV) {
2008 // case 0:
2009 // <SectionStmt[0]>;
2010 // break;
2011 // ...
2012 // case <NumSection> - 1:
2013 // <SectionStmt[<NumSection> - 1]>;
2014 // break;
2015 // }
2016 // .omp.sections.exit:
2017 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2018 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2019 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2020 CS == nullptr ? 1 : CS->size());
2021 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002022 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002023 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002024 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2025 CGF.EmitBlock(CaseBB);
2026 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002027 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002028 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002029 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002030 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002031 } else {
2032 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2033 CGF.EmitBlock(CaseBB);
2034 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2035 CGF.EmitStmt(Stmt);
2036 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002037 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002038 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002039 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002040
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002041 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2042 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002043 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002044 // initialization of firstprivate variables and post-update of lastprivate
2045 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002046 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2047 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2048 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002049 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002050 CGF.EmitOMPPrivateClause(S, LoopScope);
2051 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2052 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2053 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002054
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002055 // Emit static non-chunked loop.
2056 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2057 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
2058 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2059 UB.getAddress(), ST.getAddress());
2060 // UB = min(UB, GlobalUB);
2061 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2062 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2063 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2064 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2065 // IV = LB;
2066 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2067 // while (idx <= UB) { BODY; ++idx; }
2068 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2069 [](CodeGenFunction &) {});
2070 // Tell the runtime we are done.
2071 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2072 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002073 // Emit post-update of the reduction variables if IsLastIter != 0.
2074 emitPostUpdateForReductionClause(
2075 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2076 return CGF.Builder.CreateIsNotNull(
2077 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2078 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002079
2080 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2081 if (HasLastprivates)
2082 CGF.EmitOMPLastprivateClauseFinal(
2083 S, CGF.Builder.CreateIsNotNull(
2084 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002085 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002086
2087 bool HasCancel = false;
2088 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2089 HasCancel = OSD->hasCancel();
2090 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2091 HasCancel = OPSD->hasCancel();
2092 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2093 HasCancel);
2094 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2095 // clause. Otherwise the barrier will be generated by the codegen for the
2096 // directive.
2097 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002098 // Emit implicit barrier to synchronize threads and avoid data races on
2099 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002100 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2101 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002102 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002103}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002104
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002105void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002106 {
2107 OMPLexicalScope Scope(*this, S);
2108 EmitSections(S);
2109 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002110 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002111 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002112 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2113 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002114 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002115}
2116
2117void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002119 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002120 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002121 OMPLexicalScope Scope(*this, S);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002122 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2123 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002124}
2125
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002126void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002127 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002128 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002129 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002130 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002131 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002132 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002133 // Build a list of copyprivate variables along with helper expressions
2134 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002135 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002136 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002137 DestExprs.append(C->destination_exprs().begin(),
2138 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002139 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002140 AssignmentOps.append(C->assignment_ops().begin(),
2141 C->assignment_ops().end());
2142 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002143 // Emit code for 'single' region along with 'copyprivate' clauses
2144 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2145 Action.Enter(CGF);
2146 OMPPrivateScope SingleScope(CGF);
2147 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2148 CGF.EmitOMPPrivateClause(S, SingleScope);
2149 (void)SingleScope.Privatize();
2150 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2151 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002152 {
2153 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00002154 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2155 CopyprivateVars, DestExprs,
2156 SrcExprs, AssignmentOps);
2157 }
2158 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2159 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002160 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002161 CGM.getOpenMPRuntime().emitBarrierCall(
2162 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002163 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002164 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002165}
2166
Alexey Bataev8d690652014-12-04 07:23:53 +00002167void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002168 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2169 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002170 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002171 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002172 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002173 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002174}
2175
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002176void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002177 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2178 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002179 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002180 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002181 Expr *Hint = nullptr;
2182 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2183 Hint = HintClause->getHint();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002184 OMPLexicalScope Scope(*this, S);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002185 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2186 S.getDirectiveName().getAsString(),
2187 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002188}
2189
Alexey Bataev671605e2015-04-13 05:28:11 +00002190void CodeGenFunction::EmitOMPParallelForDirective(
2191 const OMPParallelForDirective &S) {
2192 // Emit directive as a combined directive that consists of two implicit
2193 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002194 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002195 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002196 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002197 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002198}
2199
Alexander Musmane4e893b2014-09-23 09:33:00 +00002200void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002201 const OMPParallelForSimdDirective &S) {
2202 // Emit directive as a combined directive that consists of two implicit
2203 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002204 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002205 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002206 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002207 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002208}
2209
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002210void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002211 const OMPParallelSectionsDirective &S) {
2212 // Emit directive as a combined directive that consists of two implicit
2213 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002214 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2215 CGF.EmitSections(S);
2216 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002217 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002218}
2219
Alexey Bataev62b63b12015-03-10 07:28:44 +00002220void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2221 // Emit outlined function for task construct.
2222 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2223 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2224 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002225 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002226 // The first function argument for tasks is a thread id, the second one is a
2227 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002228 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2229 // Get list of private variables.
2230 llvm::SmallVector<const Expr *, 8> PrivateVars;
2231 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002232 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002233 auto IRef = C->varlist_begin();
2234 for (auto *IInit : C->private_copies()) {
2235 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2236 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2237 PrivateVars.push_back(*IRef);
2238 PrivateCopies.push_back(IInit);
2239 }
2240 ++IRef;
2241 }
2242 }
2243 EmittedAsPrivate.clear();
2244 // Get list of firstprivate variables.
2245 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2246 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2247 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002248 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002249 auto IRef = C->varlist_begin();
2250 auto IElemInitRef = C->inits().begin();
2251 for (auto *IInit : C->private_copies()) {
2252 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2253 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2254 FirstprivateVars.push_back(*IRef);
2255 FirstprivateCopies.push_back(IInit);
2256 FirstprivateInits.push_back(*IElemInitRef);
2257 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002258 ++IRef;
2259 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002260 }
2261 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002262 // Build list of dependences.
2263 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2264 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002265 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002266 for (auto *IRef : C->varlists()) {
2267 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2268 }
2269 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002270 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002271 CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002272 // Set proper addresses for generated private copies.
2273 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002274 {
2275 OMPPrivateScope Scope(CGF);
2276 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
2277 auto *CopyFn = CGF.Builder.CreateLoad(
2278 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2279 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2280 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2281 // Map privates.
2282 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2283 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2284 CallArgs.push_back(PrivatesPtr);
2285 for (auto *E : PrivateVars) {
2286 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2287 Address PrivatePtr =
2288 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2289 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2290 CallArgs.push_back(PrivatePtr.getPointer());
2291 }
2292 for (auto *E : FirstprivateVars) {
2293 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2294 Address PrivatePtr =
2295 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2296 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2297 CallArgs.push_back(PrivatePtr.getPointer());
2298 }
2299 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2300 for (auto &&Pair : PrivatePtrs) {
2301 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2302 CGF.getContext().getDeclAlign(Pair.first));
2303 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2304 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002305 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002306 (void)Scope.Privatize();
2307 if (*PartId) {
2308 // TODO: emit code for untied tasks.
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002309 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002310 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002311 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002312 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002313 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2314 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002315 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002316 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002317 // Check if the task is final
2318 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002319 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002320 // If the condition constant folds and can be elided, try to avoid emitting
2321 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002322 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002323 bool CondConstant;
2324 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2325 Final.setInt(CondConstant);
2326 else
2327 Final.setPointer(EvaluateExprAsBool(Cond));
2328 } else {
2329 // By default the task is not final.
2330 Final.setInt(/*IntVal=*/false);
2331 }
2332 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002333 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002334 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2335 if (C->getNameModifier() == OMPD_unknown ||
2336 C->getNameModifier() == OMPD_task) {
2337 IfCond = C->getCondition();
2338 break;
2339 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002340 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002341 OMPLexicalScope Scope(*this, S);
Alexey Bataev9e034042015-05-05 04:05:12 +00002342 CGM.getOpenMPRuntime().emitTaskCall(
2343 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002344 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002345 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002346}
2347
Alexey Bataev9f797f32015-02-05 05:57:51 +00002348void CodeGenFunction::EmitOMPTaskyieldDirective(
2349 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002350 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002351}
2352
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002353void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002354 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002355}
2356
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002357void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2358 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002359}
2360
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002361void CodeGenFunction::EmitOMPTaskgroupDirective(
2362 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002363 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2364 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002365 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002366 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002367 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002368 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2369}
2370
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002371void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002372 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002373 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002374 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2375 FlushClause->varlist_end());
2376 }
2377 return llvm::None;
2378 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002379}
2380
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002381void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2382 // Emit the loop iteration variable.
2383 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2384 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2385 EmitVarDecl(*IVDecl);
2386
2387 // Emit the iterations count variable.
2388 // If it is not a variable, Sema decided to calculate iterations count on each
2389 // iteration (e.g., it is foldable into a constant).
2390 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2391 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2392 // Emit calculation of the iterations count.
2393 EmitIgnoredExpr(S.getCalcLastIteration());
2394 }
2395
2396 auto &RT = CGM.getOpenMPRuntime();
2397
2398 // Check pre-condition.
2399 {
2400 // Skip the entire loop if we don't meet the precondition.
2401 // If the condition constant folds and can be elided, avoid emitting the
2402 // whole loop.
2403 bool CondConstant;
2404 llvm::BasicBlock *ContBlock = nullptr;
2405 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2406 if (!CondConstant)
2407 return;
2408 } else {
2409 auto *ThenBlock = createBasicBlock("omp.precond.then");
2410 ContBlock = createBasicBlock("omp.precond.end");
2411 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2412 getProfileCount(&S));
2413 EmitBlock(ThenBlock);
2414 incrementProfileCounter(&S);
2415 }
2416
2417 // Emit 'then' code.
2418 {
2419 // Emit helper vars inits.
2420 LValue LB =
2421 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2422 LValue UB =
2423 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2424 LValue ST =
2425 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2426 LValue IL =
2427 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2428
2429 OMPPrivateScope LoopScope(*this);
2430 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
2431 S.private_counters());
2432 (void)LoopScope.Privatize();
2433
2434 // Detect the distribute schedule kind and chunk.
2435 llvm::Value *Chunk = nullptr;
2436 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2437 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2438 ScheduleKind = C->getDistScheduleKind();
2439 if (const auto *Ch = C->getChunkSize()) {
2440 Chunk = EmitScalarExpr(Ch);
2441 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2442 S.getIterationVariable()->getType(),
2443 S.getLocStart());
2444 }
2445 }
2446 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2447 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2448
2449 // OpenMP [2.10.8, distribute Construct, Description]
2450 // If dist_schedule is specified, kind must be static. If specified,
2451 // iterations are divided into chunks of size chunk_size, chunks are
2452 // assigned to the teams of the league in a round-robin fashion in the
2453 // order of the team number. When no chunk_size is specified, the
2454 // iteration space is divided into chunks that are approximately equal
2455 // in size, and at most one chunk is distributed to each team of the
2456 // league. The size of the chunks is unspecified in this case.
2457 if (RT.isStaticNonchunked(ScheduleKind,
2458 /* Chunked */ Chunk != nullptr)) {
2459 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2460 IVSize, IVSigned, /* Ordered = */ false,
2461 IL.getAddress(), LB.getAddress(),
2462 UB.getAddress(), ST.getAddress());
2463 auto LoopExit =
2464 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2465 // UB = min(UB, GlobalUB);
2466 EmitIgnoredExpr(S.getEnsureUpperBound());
2467 // IV = LB;
2468 EmitIgnoredExpr(S.getInit());
2469 // while (idx <= UB) { BODY; ++idx; }
2470 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2471 S.getInc(),
2472 [&S, LoopExit](CodeGenFunction &CGF) {
2473 CGF.EmitOMPLoopBody(S, LoopExit);
2474 CGF.EmitStopPoint(&S);
2475 },
2476 [](CodeGenFunction &) {});
2477 EmitBlock(LoopExit.getBlock());
2478 // Tell the runtime we are done.
2479 RT.emitForStaticFinish(*this, S.getLocStart());
2480 } else {
2481 // Emit the outer loop, which requests its work chunk [LB..UB] from
2482 // runtime and runs the inner loop to process it.
2483 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2484 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2485 IL.getAddress(), Chunk);
2486 }
2487 }
2488
2489 // We're now done with the loop, so jump to the continuation block.
2490 if (ContBlock) {
2491 EmitBranch(ContBlock);
2492 EmitBlock(ContBlock, true);
2493 }
2494 }
2495}
2496
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002497void CodeGenFunction::EmitOMPDistributeDirective(
2498 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002499 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002500 CGF.EmitOMPDistributeLoop(S);
2501 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002502 OMPLexicalScope Scope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002503 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2504 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002505}
2506
Alexey Bataev5f600d62015-09-29 03:48:57 +00002507static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2508 const CapturedStmt *S) {
2509 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2510 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2511 CGF.CapturedStmtInfo = &CapStmtInfo;
2512 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2513 Fn->addFnAttr(llvm::Attribute::NoInline);
2514 return Fn;
2515}
2516
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002517void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002518 if (!S.getAssociatedStmt())
2519 return;
Alexey Bataev5f600d62015-09-29 03:48:57 +00002520 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002521 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2522 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002523 if (C) {
2524 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2525 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2526 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2527 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2528 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2529 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002530 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002531 CGF.EmitStmt(
2532 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2533 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002534 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002535 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002536 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002537}
2538
Alexey Bataevb57056f2015-01-22 06:17:56 +00002539static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002540 QualType SrcType, QualType DestType,
2541 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002542 assert(CGF.hasScalarEvaluationKind(DestType) &&
2543 "DestType must have scalar evaluation kind.");
2544 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2545 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002546 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2547 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002548 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002549 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002550}
2551
2552static CodeGenFunction::ComplexPairTy
2553convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002554 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002555 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2556 "DestType must have complex evaluation kind.");
2557 CodeGenFunction::ComplexPairTy ComplexVal;
2558 if (Val.isScalar()) {
2559 // Convert the input element to the element type of the complex.
2560 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002561 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2562 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002563 ComplexVal = CodeGenFunction::ComplexPairTy(
2564 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2565 } else {
2566 assert(Val.isComplex() && "Must be a scalar or complex.");
2567 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2568 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2569 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002570 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002571 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002572 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002573 }
2574 return ComplexVal;
2575}
2576
Alexey Bataev5e018f92015-04-23 06:35:10 +00002577static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2578 LValue LVal, RValue RVal) {
2579 if (LVal.isGlobalReg()) {
2580 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2581 } else {
2582 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2583 : llvm::Monotonic,
2584 LVal.isVolatile(), /*IsInit=*/false);
2585 }
2586}
2587
Alexey Bataev8524d152016-01-21 12:35:58 +00002588void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2589 QualType RValTy, SourceLocation Loc) {
2590 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002591 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002592 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2593 *this, RVal, RValTy, LVal.getType(), Loc)),
2594 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002595 break;
2596 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002597 EmitStoreOfComplex(
2598 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002599 /*isInit=*/false);
2600 break;
2601 case TEK_Aggregate:
2602 llvm_unreachable("Must be a scalar or complex.");
2603 }
2604}
2605
Alexey Bataevb57056f2015-01-22 06:17:56 +00002606static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2607 const Expr *X, const Expr *V,
2608 SourceLocation Loc) {
2609 // v = x;
2610 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2611 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2612 LValue XLValue = CGF.EmitLValue(X);
2613 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002614 RValue Res = XLValue.isGlobalReg()
2615 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2616 : CGF.EmitAtomicLoad(XLValue, Loc,
2617 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002618 : llvm::Monotonic,
2619 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002620 // OpenMP, 2.12.6, atomic Construct
2621 // Any atomic construct with a seq_cst clause forces the atomically
2622 // performed operation to include an implicit flush operation without a
2623 // list.
2624 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002625 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002626 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002627}
2628
Alexey Bataevb8329262015-02-27 06:33:30 +00002629static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2630 const Expr *X, const Expr *E,
2631 SourceLocation Loc) {
2632 // x = expr;
2633 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002634 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002635 // OpenMP, 2.12.6, atomic Construct
2636 // Any atomic construct with a seq_cst clause forces the atomically
2637 // performed operation to include an implicit flush operation without a
2638 // list.
2639 if (IsSeqCst)
2640 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2641}
2642
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002643static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2644 RValue Update,
2645 BinaryOperatorKind BO,
2646 llvm::AtomicOrdering AO,
2647 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002648 auto &Context = CGF.CGM.getContext();
2649 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002650 // expression is simple and atomic is allowed for the given type for the
2651 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002652 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002653 !Update.getScalarVal()->getType()->isIntegerTy() ||
2654 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2655 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002656 X.getAddress().getElementType())) ||
2657 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002658 !Context.getTargetInfo().hasBuiltinAtomic(
2659 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002660 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002661
2662 llvm::AtomicRMWInst::BinOp RMWOp;
2663 switch (BO) {
2664 case BO_Add:
2665 RMWOp = llvm::AtomicRMWInst::Add;
2666 break;
2667 case BO_Sub:
2668 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002669 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002670 RMWOp = llvm::AtomicRMWInst::Sub;
2671 break;
2672 case BO_And:
2673 RMWOp = llvm::AtomicRMWInst::And;
2674 break;
2675 case BO_Or:
2676 RMWOp = llvm::AtomicRMWInst::Or;
2677 break;
2678 case BO_Xor:
2679 RMWOp = llvm::AtomicRMWInst::Xor;
2680 break;
2681 case BO_LT:
2682 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2683 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2684 : llvm::AtomicRMWInst::Max)
2685 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2686 : llvm::AtomicRMWInst::UMax);
2687 break;
2688 case BO_GT:
2689 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2690 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2691 : llvm::AtomicRMWInst::Min)
2692 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2693 : llvm::AtomicRMWInst::UMin);
2694 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002695 case BO_Assign:
2696 RMWOp = llvm::AtomicRMWInst::Xchg;
2697 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002698 case BO_Mul:
2699 case BO_Div:
2700 case BO_Rem:
2701 case BO_Shl:
2702 case BO_Shr:
2703 case BO_LAnd:
2704 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002705 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002706 case BO_PtrMemD:
2707 case BO_PtrMemI:
2708 case BO_LE:
2709 case BO_GE:
2710 case BO_EQ:
2711 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002712 case BO_AddAssign:
2713 case BO_SubAssign:
2714 case BO_AndAssign:
2715 case BO_OrAssign:
2716 case BO_XorAssign:
2717 case BO_MulAssign:
2718 case BO_DivAssign:
2719 case BO_RemAssign:
2720 case BO_ShlAssign:
2721 case BO_ShrAssign:
2722 case BO_Comma:
2723 llvm_unreachable("Unsupported atomic update operation");
2724 }
2725 auto *UpdateVal = Update.getScalarVal();
2726 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2727 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002728 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002729 X.getType()->hasSignedIntegerRepresentation());
2730 }
John McCall7f416cc2015-09-08 08:05:57 +00002731 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002732 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002733}
2734
Alexey Bataev5e018f92015-04-23 06:35:10 +00002735std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002736 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2737 llvm::AtomicOrdering AO, SourceLocation Loc,
2738 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2739 // Update expressions are allowed to have the following forms:
2740 // x binop= expr; -> xrval + expr;
2741 // x++, ++x -> xrval + 1;
2742 // x--, --x -> xrval - 1;
2743 // x = x binop expr; -> xrval binop expr
2744 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002745 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2746 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002747 if (X.isGlobalReg()) {
2748 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2749 // 'xrval'.
2750 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2751 } else {
2752 // Perform compare-and-swap procedure.
2753 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002754 }
2755 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002756 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002757}
2758
2759static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2760 const Expr *X, const Expr *E,
2761 const Expr *UE, bool IsXLHSInRHSPart,
2762 SourceLocation Loc) {
2763 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2764 "Update expr in 'atomic update' must be a binary operator.");
2765 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2766 // Update expressions are allowed to have the following forms:
2767 // x binop= expr; -> xrval + expr;
2768 // x++, ++x -> xrval + 1;
2769 // x--, --x -> xrval - 1;
2770 // x = x binop expr; -> xrval binop expr
2771 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002772 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002773 LValue XLValue = CGF.EmitLValue(X);
2774 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002775 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002776 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2777 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2778 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2779 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2780 auto Gen =
2781 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2782 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2783 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2784 return CGF.EmitAnyExpr(UE);
2785 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002786 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2787 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2788 // OpenMP, 2.12.6, atomic Construct
2789 // Any atomic construct with a seq_cst clause forces the atomically
2790 // performed operation to include an implicit flush operation without a
2791 // list.
2792 if (IsSeqCst)
2793 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2794}
2795
2796static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002797 QualType SourceType, QualType ResType,
2798 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002799 switch (CGF.getEvaluationKind(ResType)) {
2800 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002801 return RValue::get(
2802 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002803 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002804 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002805 return RValue::getComplex(Res.first, Res.second);
2806 }
2807 case TEK_Aggregate:
2808 break;
2809 }
2810 llvm_unreachable("Must be a scalar or complex.");
2811}
2812
2813static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2814 bool IsPostfixUpdate, const Expr *V,
2815 const Expr *X, const Expr *E,
2816 const Expr *UE, bool IsXLHSInRHSPart,
2817 SourceLocation Loc) {
2818 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2819 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2820 RValue NewVVal;
2821 LValue VLValue = CGF.EmitLValue(V);
2822 LValue XLValue = CGF.EmitLValue(X);
2823 RValue ExprRValue = CGF.EmitAnyExpr(E);
2824 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2825 QualType NewVValType;
2826 if (UE) {
2827 // 'x' is updated with some additional value.
2828 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2829 "Update expr in 'atomic capture' 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;
2837 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2838 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2839 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2840 NewVValType = XRValExpr->getType();
2841 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2842 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2843 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2844 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2845 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2846 RValue Res = CGF.EmitAnyExpr(UE);
2847 NewVVal = IsPostfixUpdate ? XRValue : Res;
2848 return Res;
2849 };
2850 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2851 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2852 if (Res.first) {
2853 // 'atomicrmw' instruction was generated.
2854 if (IsPostfixUpdate) {
2855 // Use old value from 'atomicrmw'.
2856 NewVVal = Res.second;
2857 } else {
2858 // 'atomicrmw' does not provide new value, so evaluate it using old
2859 // value of 'x'.
2860 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2861 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2862 NewVVal = CGF.EmitAnyExpr(UE);
2863 }
2864 }
2865 } else {
2866 // 'x' is simply rewritten with some 'expr'.
2867 NewVValType = X->getType().getNonReferenceType();
2868 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002869 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002870 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2871 NewVVal = XRValue;
2872 return ExprRValue;
2873 };
2874 // Try to perform atomicrmw xchg, otherwise simple exchange.
2875 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2876 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2877 Loc, Gen);
2878 if (Res.first) {
2879 // 'atomicrmw' instruction was generated.
2880 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2881 }
2882 }
2883 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002884 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002885 // OpenMP, 2.12.6, atomic Construct
2886 // Any atomic construct with a seq_cst clause forces the atomically
2887 // performed operation to include an implicit flush operation without a
2888 // list.
2889 if (IsSeqCst)
2890 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2891}
2892
Alexey Bataevb57056f2015-01-22 06:17:56 +00002893static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002894 bool IsSeqCst, bool IsPostfixUpdate,
2895 const Expr *X, const Expr *V, const Expr *E,
2896 const Expr *UE, bool IsXLHSInRHSPart,
2897 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002898 switch (Kind) {
2899 case OMPC_read:
2900 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2901 break;
2902 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002903 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2904 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002905 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002906 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002907 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2908 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002909 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002910 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2911 IsXLHSInRHSPart, Loc);
2912 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002913 case OMPC_if:
2914 case OMPC_final:
2915 case OMPC_num_threads:
2916 case OMPC_private:
2917 case OMPC_firstprivate:
2918 case OMPC_lastprivate:
2919 case OMPC_reduction:
2920 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002921 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002922 case OMPC_collapse:
2923 case OMPC_default:
2924 case OMPC_seq_cst:
2925 case OMPC_shared:
2926 case OMPC_linear:
2927 case OMPC_aligned:
2928 case OMPC_copyin:
2929 case OMPC_copyprivate:
2930 case OMPC_flush:
2931 case OMPC_proc_bind:
2932 case OMPC_schedule:
2933 case OMPC_ordered:
2934 case OMPC_nowait:
2935 case OMPC_untied:
2936 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002937 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002938 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002939 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002940 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002941 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002942 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002943 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002944 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002945 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002946 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002947 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002948 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002949 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002950 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002951 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002952 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2953 }
2954}
2955
2956void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002957 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002958 OpenMPClauseKind Kind = OMPC_unknown;
2959 for (auto *C : S.clauses()) {
2960 // Find first clause (skip seq_cst clause, if it is first).
2961 if (C->getClauseKind() != OMPC_seq_cst) {
2962 Kind = C->getClauseKind();
2963 break;
2964 }
2965 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002966
2967 const auto *CS =
2968 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002969 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002970 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002971 }
2972 // Processing for statements under 'atomic capture'.
2973 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2974 for (const auto *C : Compound->body()) {
2975 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2976 enterFullExpression(EWC);
2977 }
2978 }
2979 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002980
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002981 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
2982 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00002983 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002984 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2985 S.getV(), S.getExpr(), S.getUpdateExpr(),
2986 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002987 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002988 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002989 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002990}
2991
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002992std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
2993CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
2994 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
2995 bool IsOffloadEntry) {
2996 llvm::Function *OutlinedFn = nullptr;
2997 llvm::Constant *OutlinedFnID = nullptr;
2998 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2999 OMPPrivateScope PrivateScope(CGF);
3000 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3001 CGF.EmitOMPPrivateClause(S, PrivateScope);
3002 (void)PrivateScope.Privatize();
3003
3004 Action.Enter(CGF);
3005 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3006 };
3007 // Emit target region as a standalone region.
3008 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3009 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3010 return std::make_pair(OutlinedFn, OutlinedFnID);
3011}
3012
Samuel Antaobed3c462015-10-02 16:14:20 +00003013void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003014 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3015
3016 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003017 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003018
Samuel Antaoee8fb302016-01-06 13:42:12 +00003019 llvm::Function *Fn = nullptr;
3020 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003021
3022 // Check if we have any if clause associated with the directive.
3023 const Expr *IfCond = nullptr;
3024
3025 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3026 IfCond = C->getCondition();
3027 }
3028
3029 // Check if we have any device clause associated with the directive.
3030 const Expr *Device = nullptr;
3031 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3032 Device = C->getDevice();
3033 }
3034
Samuel Antaoee8fb302016-01-06 13:42:12 +00003035 // Check if we have an if clause whose conditional always evaluates to false
3036 // or if we do not have any targets specified. If so the target region is not
3037 // an offload entry point.
3038 bool IsOffloadEntry = true;
3039 if (IfCond) {
3040 bool Val;
3041 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3042 IsOffloadEntry = false;
3043 }
3044 if (CGM.getLangOpts().OMPTargetTriples.empty())
3045 IsOffloadEntry = false;
3046
3047 assert(CurFuncDecl && "No parent declaration for target region!");
3048 StringRef ParentName;
3049 // In case we have Ctors/Dtors we use the complete type variant to produce
3050 // the mangling of the device outlined kernel.
3051 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3052 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3053 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3054 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3055 else
3056 ParentName =
3057 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3058
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003059 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3060 CGM, S, ParentName, IsOffloadEntry);
3061 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003062 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003063 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003064}
3065
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003066static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3067 const OMPExecutableDirective &S,
3068 OpenMPDirectiveKind InnermostKind,
3069 const RegionCodeGenTy &CodeGen) {
3070 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003071 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3072 emitParallelOrTeamsOutlinedFunction(S,
3073 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003074
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003075 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3076 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3077 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3078 if (NT || TL) {
3079 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
3080 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
3081 /* isSigned = */ true) :
3082 CGF.Builder.getInt32(0);
3083
3084 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
3085 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
3086 /* isSigned = */ true) :
3087 CGF.Builder.getInt32(0);
3088
3089 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
3090 ThreadLimitVal, S.getLocStart());
3091 }
3092
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003093 OMPLexicalScope Scope(CGF, S);
3094 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3095 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003096 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3097 CapturedVars);
3098}
3099
3100void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003101 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003102 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003103 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003104 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3105 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003106 (void)PrivateScope.Privatize();
3107 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3108 };
3109 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003110}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003111
3112void CodeGenFunction::EmitOMPCancellationPointDirective(
3113 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003114 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3115 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003116}
3117
Alexey Bataev80909872015-07-02 11:25:17 +00003118void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003119 const Expr *IfCond = nullptr;
3120 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3121 if (C->getNameModifier() == OMPD_unknown ||
3122 C->getNameModifier() == OMPD_cancel) {
3123 IfCond = C->getCondition();
3124 break;
3125 }
3126 }
3127 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003128 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003129}
3130
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003131CodeGenFunction::JumpDest
3132CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3133 if (Kind == OMPD_parallel || Kind == OMPD_task)
3134 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003135 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003136 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003137 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003138}
Michael Wong65f367f2015-07-21 13:44:28 +00003139
3140// Generate the instructions for '#pragma omp target data' directive.
3141void CodeGenFunction::EmitOMPTargetDataDirective(
3142 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00003143 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003144 OMPLexicalScope Scope(*this, S);
Michael Wongb5c16982015-08-11 04:52:01 +00003145 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003146 *this, OMPD_target_data, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3147 CGF.EmitStmt(
3148 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3149 });
Michael Wong65f367f2015-07-21 13:44:28 +00003150}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003151
Samuel Antaodf67fc42016-01-19 19:15:56 +00003152void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3153 const OMPTargetEnterDataDirective &S) {
3154 // TODO: codegen for target enter data.
3155}
3156
Samuel Antao72590762016-01-19 20:04:50 +00003157void CodeGenFunction::EmitOMPTargetExitDataDirective(
3158 const OMPTargetExitDataDirective &S) {
3159 // TODO: codegen for target exit data.
3160}
3161
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003162void CodeGenFunction::EmitOMPTargetParallelDirective(
3163 const OMPTargetParallelDirective &S) {
3164 // TODO: codegen for target parallel.
3165}
3166
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003167void CodeGenFunction::EmitOMPTargetParallelForDirective(
3168 const OMPTargetParallelForDirective &S) {
3169 // TODO: codegen for target parallel for.
3170}
3171
Alexey Bataev49f6e782015-12-01 04:18:41 +00003172void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
3173 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003174 OMPLexicalScope Scope(*this, S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003175 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003176 *this, OMPD_taskloop, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3177 CGF.EmitStmt(
3178 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3179 });
Alexey Bataev49f6e782015-12-01 04:18:41 +00003180}
3181
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003182void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3183 const OMPTaskLoopSimdDirective &S) {
3184 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003185 OMPLexicalScope Scope(*this, S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003186 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003187 *this, OMPD_taskloop_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3188 CGF.EmitStmt(
3189 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3190 });
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003191}
3192