blob: ddad5cdbcc9b99c3c26dcb70e671b0ec59476c70 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Alexey Bataev4ba78a42016-04-27 07:56:03 +000029class OMPLexicalScope final : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 bool AsInlined = false)
58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +000060 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000061 if (AsInlined) {
62 if (S.hasAssociatedStmt()) {
63 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
64 for (auto &C : CS->captures()) {
65 if (C.capturesVariable() || C.capturesVariableByCopy()) {
66 auto *VD = C.getCapturedVar();
67 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
68 isCapturedVar(CGF, VD) ||
69 (CGF.CapturedStmtInfo &&
70 InlinedShareds.isGlobalVarCaptured(VD)),
71 VD->getType().getNonReferenceType(), VK_LValue,
72 SourceLocation());
73 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
74 return CGF.EmitLValue(&DRE).getAddress();
75 });
76 }
77 }
78 (void)InlinedShareds.Privatize();
79 }
80 }
Alexey Bataev3392d762016-02-16 11:18:12 +000081 }
82};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000083
Alexey Bataev5a3af132016-03-29 08:58:54 +000084/// Private scope for OpenMP loop-based directives, that supports capturing
85/// of used expression from loop statement.
86class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
87 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
88 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
89 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
90 for (const auto *I : PreInits->decls())
91 CGF.EmitVarDecl(cast<VarDecl>(*I));
92 }
93 }
94 }
95
96public:
97 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
98 : CodeGenFunction::RunCleanupsScope(CGF) {
99 emitPreInitStmt(CGF, S);
100 }
101};
102
Alexey Bataev3392d762016-02-16 11:18:12 +0000103} // namespace
104
Alexey Bataev1189bd02016-01-26 12:20:39 +0000105llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
106 auto &C = getContext();
107 llvm::Value *Size = nullptr;
108 auto SizeInChars = C.getTypeSizeInChars(Ty);
109 if (SizeInChars.isZero()) {
110 // getTypeSizeInChars() returns 0 for a VLA.
111 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
112 llvm::Value *ArraySize;
113 std::tie(ArraySize, Ty) = getVLASize(VAT);
114 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
115 }
116 SizeInChars = C.getTypeSizeInChars(Ty);
117 if (SizeInChars.isZero())
118 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
119 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
120 } else
121 Size = CGM.getSize(SizeInChars);
122 return Size;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 const RecordDecl *RD = S.getCapturedRecordDecl();
128 auto CurField = RD->field_begin();
129 auto CurCap = S.captures().begin();
130 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
131 E = S.capture_init_end();
132 I != E; ++I, ++CurField, ++CurCap) {
133 if (CurField->hasCapturedVLAType()) {
134 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000135 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000136 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000137 } else if (CurCap->capturesThis())
138 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000139 else if (CurCap->capturesVariableByCopy()) {
140 llvm::Value *CV =
141 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
142
143 // If the field is not a pointer, we need to save the actual value
144 // and load it as a void pointer.
145 if (!CurField->getType()->isAnyPointerType()) {
146 auto &Ctx = getContext();
147 auto DstAddr = CreateMemTemp(
148 Ctx.getUIntPtrType(),
149 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
150 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
151
152 auto *SrcAddrVal = EmitScalarConversion(
153 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
154 Ctx.getPointerType(CurField->getType()), SourceLocation());
155 LValue SrcLV =
156 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
157
158 // Store the value using the source type pointer.
159 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
160
161 // Load the value using the destination type pointer.
162 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
163 }
164 CapturedVars.push_back(CV);
165 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000166 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000167 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000168 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000169 }
170}
171
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000172static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
173 StringRef Name, LValue AddrLV,
174 bool isReferenceType = false) {
175 ASTContext &Ctx = CGF.getContext();
176
177 auto *CastedPtr = CGF.EmitScalarConversion(
178 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
179 Ctx.getPointerType(DstType), SourceLocation());
180 auto TmpAddr =
181 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
182 .getAddress();
183
184 // If we are dealing with references we need to return the address of the
185 // reference instead of the reference of the value.
186 if (isReferenceType) {
187 QualType RefType = Ctx.getLValueReferenceType(DstType);
188 auto *RefVal = TmpAddr.getPointer();
189 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
190 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
191 CGF.EmitScalarInit(RefVal, TmpLVal);
192 }
193
194 return TmpAddr;
195}
196
Alexey Bataev2377fe92015-09-10 08:12:02 +0000197llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000198CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000199 assert(
200 CapturedStmtInfo &&
201 "CapturedStmtInfo should be set when generating the captured function");
202 const CapturedDecl *CD = S.getCapturedDecl();
203 const RecordDecl *RD = S.getCapturedRecordDecl();
204 assert(CD->hasBody() && "missing CapturedDecl body");
205
206 // Build the argument list.
207 ASTContext &Ctx = CGM.getContext();
208 FunctionArgList Args;
209 Args.append(CD->param_begin(),
210 std::next(CD->param_begin(), CD->getContextParamPosition()));
211 auto I = S.captures().begin();
212 for (auto *FD : RD->fields()) {
213 QualType ArgType = FD->getType();
214 IdentifierInfo *II = nullptr;
215 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000216
217 // If this is a capture by copy and the type is not a pointer, the outlined
218 // function argument type should be uintptr and the value properly casted to
219 // uintptr. This is necessary given that the runtime library is only able to
220 // deal with pointers. We can pass in the same way the VLA type sizes to the
221 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000222 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
223 I->capturesVariableArrayType())
224 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225
226 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000227 CapVar = I->getCapturedVar();
228 II = CapVar->getIdentifier();
229 } else if (I->capturesThis())
230 II = &getContext().Idents.get("this");
231 else {
232 assert(I->capturesVariableArrayType());
233 II = &getContext().Idents.get("vla");
234 }
235 if (ArgType->isVariablyModifiedType())
236 ArgType = getContext().getVariableArrayDecayedType(ArgType);
237 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
238 FD->getLocation(), II, ArgType));
239 ++I;
240 }
241 Args.append(
242 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
243 CD->param_end());
244
245 // Create the function declaration.
246 FunctionType::ExtInfo ExtInfo;
247 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000248 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000249 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
250
251 llvm::Function *F = llvm::Function::Create(
252 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
253 CapturedStmtInfo->getHelperName(), &CGM.getModule());
254 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
255 if (CD->isNothrow())
256 F->addFnAttr(llvm::Attribute::NoUnwind);
257
258 // Generate the function.
259 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
260 CD->getBody()->getLocStart());
261 unsigned Cnt = CD->getContextParamPosition();
262 I = S.captures().begin();
263 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000264 // If we are capturing a pointer by copy we don't need to do anything, just
265 // use the value that we get from the arguments.
266 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
267 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000268 ++Cnt;
269 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000270 continue;
271 }
272
Alexey Bataev2377fe92015-09-10 08:12:02 +0000273 LValue ArgLVal =
274 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
275 AlignmentSource::Decl);
276 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000277 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000278 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
279 Args[Cnt]->getName(), ArgLVal),
280 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000281 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000282 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000283 auto VAT = FD->getCapturedVLAType();
284 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
285 } else if (I->capturesVariable()) {
286 auto *Var = I->getCapturedVar();
287 QualType VarTy = Var->getType();
288 Address ArgAddr = ArgLVal.getAddress();
289 if (!VarTy->isReferenceType()) {
290 ArgAddr = EmitLoadOfReference(
291 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
292 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000293 setAddrOfLocalVar(
294 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000295 } else if (I->capturesVariableByCopy()) {
296 assert(!FD->getType()->isAnyPointerType() &&
297 "Not expecting a captured pointer.");
298 auto *Var = I->getCapturedVar();
299 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000300 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
301 Args[Cnt]->getName(), ArgLVal,
302 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000303 } else {
304 // If 'this' is captured, load it into CXXThisValue.
305 assert(I->capturesThis());
306 CXXThisValue =
307 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
308 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000309 ++Cnt;
310 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000311 }
312
Serge Pavlov3a561452015-12-06 14:32:39 +0000313 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 CapturedStmtInfo->EmitBody(*this, CD->getBody());
315 FinishFunction(CD->getBodyRBrace());
316
317 return F;
318}
319
Alexey Bataev9959db52014-05-06 10:08:46 +0000320//===----------------------------------------------------------------------===//
321// OpenMP Directive Emission
322//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000323void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000324 Address DestAddr, Address SrcAddr, QualType OriginalType,
325 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000326 // Perform element-by-element initialization.
327 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000328
329 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000330 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000331 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
332 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
333
334 auto SrcBegin = SrcAddr.getPointer();
335 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000336 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000337 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
338 // The basic structure here is a while-do loop.
339 auto BodyBB = createBasicBlock("omp.arraycpy.body");
340 auto DoneBB = createBasicBlock("omp.arraycpy.done");
341 auto IsEmpty =
342 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
343 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000344
Alexey Bataev420d45b2015-04-14 05:11:24 +0000345 // Enter the loop body, making that address the current address.
346 auto EntryBB = Builder.GetInsertBlock();
347 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000348
349 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
350
351 llvm::PHINode *SrcElementPHI =
352 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
353 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
354 Address SrcElementCurrent =
355 Address(SrcElementPHI,
356 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
357
358 llvm::PHINode *DestElementPHI =
359 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
360 DestElementPHI->addIncoming(DestBegin, EntryBB);
361 Address DestElementCurrent =
362 Address(DestElementPHI,
363 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000364
Alexey Bataev420d45b2015-04-14 05:11:24 +0000365 // Emit copy.
366 CopyGen(DestElementCurrent, SrcElementCurrent);
367
368 // Shift the address forward by one element.
369 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000370 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000371 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000372 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000373 // Check whether we've reached the end.
374 auto Done =
375 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
376 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000377 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
378 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000379
380 // Done.
381 EmitBlock(DoneBB, /*IsFinished=*/true);
382}
383
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000384/// Check if the combiner is a call to UDR combiner and if it is so return the
385/// UDR decl used for reduction.
386static const OMPDeclareReductionDecl *
387getReductionInit(const Expr *ReductionOp) {
388 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
389 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
390 if (auto *DRE =
391 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
392 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
393 return DRD;
394 return nullptr;
395}
396
397static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
398 const OMPDeclareReductionDecl *DRD,
399 const Expr *InitOp,
400 Address Private, Address Original,
401 QualType Ty) {
402 if (DRD->getInitializer()) {
403 std::pair<llvm::Function *, llvm::Function *> Reduction =
404 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
405 auto *CE = cast<CallExpr>(InitOp);
406 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
407 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
408 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
409 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
410 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
411 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
412 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
413 [=]() -> Address { return Private; });
414 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
415 [=]() -> Address { return Original; });
416 (void)PrivateScope.Privatize();
417 RValue Func = RValue::get(Reduction.second);
418 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
419 CGF.EmitIgnoredExpr(InitOp);
420 } else {
421 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
422 auto *GV = new llvm::GlobalVariable(
423 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
424 llvm::GlobalValue::PrivateLinkage, Init, ".init");
425 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
426 RValue InitRVal;
427 switch (CGF.getEvaluationKind(Ty)) {
428 case TEK_Scalar:
429 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
430 break;
431 case TEK_Complex:
432 InitRVal =
433 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
434 break;
435 case TEK_Aggregate:
436 InitRVal = RValue::getAggregate(LV.getAddress());
437 break;
438 }
439 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
440 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
441 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
442 /*IsInitializer=*/false);
443 }
444}
445
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000446/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000447/// \param DestAddr Address of the array.
448/// \param Type Type of array.
449/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000450/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000451static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000452 QualType Type, const Expr *Init,
453 Address SrcAddr = Address::invalid()) {
454 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000455 // Perform element-by-element initialization.
456 QualType ElementTy;
457
458 // Drill down to the base element type on both arrays.
459 auto ArrayTy = Type->getAsArrayTypeUnsafe();
460 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
461 DestAddr =
462 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000463 if (DRD)
464 SrcAddr =
465 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000466
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000467 llvm::Value *SrcBegin = nullptr;
468 if (DRD)
469 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000470 auto DestBegin = DestAddr.getPointer();
471 // Cast from pointer to array type to pointer to single element.
472 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
473 // The basic structure here is a while-do loop.
474 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
475 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
476 auto IsEmpty =
477 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
478 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
479
480 // Enter the loop body, making that address the current address.
481 auto EntryBB = CGF.Builder.GetInsertBlock();
482 CGF.EmitBlock(BodyBB);
483
484 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
485
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000486 llvm::PHINode *SrcElementPHI = nullptr;
487 Address SrcElementCurrent = Address::invalid();
488 if (DRD) {
489 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
490 "omp.arraycpy.srcElementPast");
491 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
492 SrcElementCurrent =
493 Address(SrcElementPHI,
494 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
495 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000496 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
497 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
498 DestElementPHI->addIncoming(DestBegin, EntryBB);
499 Address DestElementCurrent =
500 Address(DestElementPHI,
501 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
502
503 // Emit copy.
504 {
505 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000506 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000507 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
508 SrcElementCurrent, ElementTy);
509 } else
510 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
511 /*IsInitializer=*/false);
512 }
513
514 if (DRD) {
515 // Shift the address forward by one element.
516 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
517 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
518 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000519 }
520
521 // Shift the address forward by one element.
522 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
523 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
524 // Check whether we've reached the end.
525 auto Done =
526 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
527 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
528 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
529
530 // Done.
531 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
532}
533
John McCall7f416cc2015-09-08 08:05:57 +0000534void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
535 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000536 const VarDecl *SrcVD, const Expr *Copy) {
537 if (OriginalType->isArrayType()) {
538 auto *BO = dyn_cast<BinaryOperator>(Copy);
539 if (BO && BO->getOpcode() == BO_Assign) {
540 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000541 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000542 } else {
543 // For arrays with complex element types perform element by element
544 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000545 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000546 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000547 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000548 // Working with the single array element, so have to remap
549 // destination and source variables to corresponding array
550 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000551 CodeGenFunction::OMPPrivateScope Remap(*this);
552 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000553 return DestElement;
554 });
555 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000556 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000557 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000558 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000559 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000560 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000561 } else {
562 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000563 CodeGenFunction::OMPPrivateScope Remap(*this);
564 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
565 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000566 (void)Remap.Privatize();
567 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000568 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000569 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000570}
571
Alexey Bataev69c62a92015-04-15 04:52:20 +0000572bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
573 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000574 if (!HaveInsertPoint())
575 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000576 bool FirstprivateIsLastprivate = false;
577 llvm::DenseSet<const VarDecl *> Lastprivates;
578 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
579 for (const auto *D : C->varlists())
580 Lastprivates.insert(
581 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
582 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000583 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000584 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000585 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000586 auto IRef = C->varlist_begin();
587 auto InitsRef = C->inits().begin();
588 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000589 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000590 bool ThisFirstprivateIsLastprivate =
591 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000592 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000593 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000594 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000595 !FD->getType()->isReferenceType()) {
596 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
597 ++IRef;
598 ++InitsRef;
599 continue;
600 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000601 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000602 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000603 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000604 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
605 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
606 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000607 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
608 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
609 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000610 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000611 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000612 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000613 // Emit VarDecl with copy init for arrays.
614 // Get the address of the original variable captured in current
615 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000616 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000617 auto Emission = EmitAutoVarAlloca(*VD);
618 auto *Init = VD->getInit();
619 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
620 // Perform simple memcpy.
621 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000622 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000623 } else {
624 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000625 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000626 [this, VDInit, Init](Address DestElement,
627 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000628 // Clean up any temporaries needed by the initialization.
629 RunCleanupsScope InitScope(*this);
630 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000631 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000632 EmitAnyExprToMem(Init, DestElement,
633 Init->getType().getQualifiers(),
634 /*IsInitializer*/ false);
635 LocalDeclMap.erase(VDInit);
636 });
637 }
638 EmitAutoVarCleanups(Emission);
639 return Emission.getAllocatedAddress();
640 });
641 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000642 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000643 // Emit private VarDecl with copy init.
644 // Remap temp VDInit variable to the address of the original
645 // variable
646 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000647 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000648 EmitDecl(*VD);
649 LocalDeclMap.erase(VDInit);
650 return GetAddrOfLocalVar(VD);
651 });
652 }
653 assert(IsRegistered &&
654 "firstprivate var already registered as private");
655 // Silence the warning about unused variable.
656 (void)IsRegistered;
657 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000658 ++IRef;
659 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000660 }
661 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000662 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000663}
664
Alexey Bataev03b340a2014-10-21 03:16:40 +0000665void CodeGenFunction::EmitOMPPrivateClause(
666 const OMPExecutableDirective &D,
667 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000668 if (!HaveInsertPoint())
669 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000670 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000671 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000672 auto IRef = C->varlist_begin();
673 for (auto IInit : C->private_copies()) {
674 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000675 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
676 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
677 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000678 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000679 // Emit private VarDecl with copy init.
680 EmitDecl(*VD);
681 return GetAddrOfLocalVar(VD);
682 });
683 assert(IsRegistered && "private var already registered as private");
684 // Silence the warning about unused variable.
685 (void)IsRegistered;
686 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000687 ++IRef;
688 }
689 }
690}
691
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000692bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000693 if (!HaveInsertPoint())
694 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000695 // threadprivate_var1 = master_threadprivate_var1;
696 // operator=(threadprivate_var2, master_threadprivate_var2);
697 // ...
698 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000699 llvm::DenseSet<const VarDecl *> CopiedVars;
700 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000701 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000702 auto IRef = C->varlist_begin();
703 auto ISrcRef = C->source_exprs().begin();
704 auto IDestRef = C->destination_exprs().begin();
705 for (auto *AssignOp : C->assignment_ops()) {
706 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000707 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000708 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000709 // Get the address of the master variable. If we are emitting code with
710 // TLS support, the address is passed from the master as field in the
711 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000712 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000713 if (getLangOpts().OpenMPUseTLS &&
714 getContext().getTargetInfo().isTLSSupported()) {
715 assert(CapturedStmtInfo->lookup(VD) &&
716 "Copyin threadprivates should have been captured!");
717 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
718 VK_LValue, (*IRef)->getExprLoc());
719 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000720 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000721 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000722 MasterAddr =
723 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
724 : CGM.GetAddrOfGlobal(VD),
725 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000726 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000727 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000728 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000729 if (CopiedVars.size() == 1) {
730 // At first check if current thread is a master thread. If it is, no
731 // need to copy data.
732 CopyBegin = createBasicBlock("copyin.not.master");
733 CopyEnd = createBasicBlock("copyin.not.master.end");
734 Builder.CreateCondBr(
735 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000736 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
737 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000738 CopyBegin, CopyEnd);
739 EmitBlock(CopyBegin);
740 }
741 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
742 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000743 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000744 }
745 ++IRef;
746 ++ISrcRef;
747 ++IDestRef;
748 }
749 }
750 if (CopyEnd) {
751 // Exit out of copying procedure for non-master thread.
752 EmitBlock(CopyEnd, /*IsFinished=*/true);
753 return true;
754 }
755 return false;
756}
757
Alexey Bataev38e89532015-04-16 04:54:05 +0000758bool CodeGenFunction::EmitOMPLastprivateClauseInit(
759 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000760 if (!HaveInsertPoint())
761 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000762 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000763 llvm::DenseSet<const VarDecl *> SIMDLCVs;
764 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
765 auto *LoopDirective = cast<OMPLoopDirective>(&D);
766 for (auto *C : LoopDirective->counters()) {
767 SIMDLCVs.insert(
768 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
769 }
770 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000771 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000772 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000773 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000774 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
775 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000776 auto IRef = C->varlist_begin();
777 auto IDestRef = C->destination_exprs().begin();
778 for (auto *IInit : C->private_copies()) {
779 // Keep the address of the original variable for future update at the end
780 // of the loop.
781 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000782 // Taskloops do not require additional initialization, it is done in
783 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000784 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
785 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000786 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000787 DeclRefExpr DRE(
788 const_cast<VarDecl *>(OrigVD),
789 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
790 OrigVD) != nullptr,
791 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
792 return EmitLValue(&DRE).getAddress();
793 });
794 // Check if the variable is also a firstprivate: in this case IInit is
795 // not generated. Initialization of this variable will happen in codegen
796 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000797 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000798 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000799 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
800 // Emit private VarDecl with copy init.
801 EmitDecl(*VD);
802 return GetAddrOfLocalVar(VD);
803 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000804 assert(IsRegistered &&
805 "lastprivate var already registered as private");
806 (void)IsRegistered;
807 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000808 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000809 ++IRef;
810 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000811 }
812 }
813 return HasAtLeastOneLastprivate;
814}
815
816void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000817 const OMPExecutableDirective &D, bool NoFinals,
818 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000819 if (!HaveInsertPoint())
820 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000821 // Emit following code:
822 // if (<IsLastIterCond>) {
823 // orig_var1 = private_orig_var1;
824 // ...
825 // orig_varn = private_orig_varn;
826 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000827 llvm::BasicBlock *ThenBB = nullptr;
828 llvm::BasicBlock *DoneBB = nullptr;
829 if (IsLastIterCond) {
830 ThenBB = createBasicBlock(".omp.lastprivate.then");
831 DoneBB = createBasicBlock(".omp.lastprivate.done");
832 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
833 EmitBlock(ThenBB);
834 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000835 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
836 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000837 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000838 auto IC = LoopDirective->counters().begin();
839 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000840 auto *D =
841 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
842 if (NoFinals)
843 AlreadyEmittedVars.insert(D);
844 else
845 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000846 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000847 }
848 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000849 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
850 auto IRef = C->varlist_begin();
851 auto ISrcRef = C->source_exprs().begin();
852 auto IDestRef = C->destination_exprs().begin();
853 for (auto *AssignOp : C->assignment_ops()) {
854 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
855 QualType Type = PrivateVD->getType();
856 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
857 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
858 // If lastprivate variable is a loop control variable for loop-based
859 // directive, update its value before copyin back to original
860 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000861 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
862 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000863 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
864 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
865 // Get the address of the original variable.
866 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
867 // Get the address of the private variable.
868 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
869 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
870 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000871 Address(Builder.CreateLoad(PrivateAddr),
872 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000873 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000874 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000875 ++IRef;
876 ++ISrcRef;
877 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000878 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000879 if (auto *PostUpdate = C->getPostUpdateExpr())
880 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000881 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000882 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000883 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000884}
885
Alexey Bataev31300ed2016-02-04 11:27:03 +0000886static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
887 LValue BaseLV, llvm::Value *Addr) {
888 Address Tmp = Address::invalid();
889 Address TopTmp = Address::invalid();
890 Address MostTopTmp = Address::invalid();
891 BaseTy = BaseTy.getNonReferenceType();
892 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
893 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
894 Tmp = CGF.CreateMemTemp(BaseTy);
895 if (TopTmp.isValid())
896 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
897 else
898 MostTopTmp = Tmp;
899 TopTmp = Tmp;
900 BaseTy = BaseTy->getPointeeType();
901 }
902 llvm::Type *Ty = BaseLV.getPointer()->getType();
903 if (Tmp.isValid())
904 Ty = Tmp.getElementType();
905 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
906 if (Tmp.isValid()) {
907 CGF.Builder.CreateStore(Addr, Tmp);
908 return MostTopTmp;
909 }
910 return Address(Addr, BaseLV.getAlignment());
911}
912
913static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
914 LValue BaseLV) {
915 BaseTy = BaseTy.getNonReferenceType();
916 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
917 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
918 if (auto *PtrTy = BaseTy->getAs<PointerType>())
919 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
920 else {
921 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
922 BaseTy->castAs<ReferenceType>());
923 }
924 BaseTy = BaseTy->getPointeeType();
925 }
926 return CGF.MakeAddrLValue(
927 Address(
928 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
929 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
930 BaseLV.getAlignment()),
931 BaseLV.getType(), BaseLV.getAlignmentSource());
932}
933
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000934void CodeGenFunction::EmitOMPReductionClauseInit(
935 const OMPExecutableDirective &D,
936 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000937 if (!HaveInsertPoint())
938 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000939 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000940 auto ILHS = C->lhs_exprs().begin();
941 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000943 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000944 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000945 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000946 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
947 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000948 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000949 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
950 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
951 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
952 Base = TempOASE->getBase()->IgnoreParenImpCasts();
953 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
954 Base = TempASE->getBase()->IgnoreParenImpCasts();
955 auto *DE = cast<DeclRefExpr>(Base);
956 auto *OrigVD = cast<VarDecl>(DE->getDecl());
957 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
958 auto OASELValueUB =
959 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
960 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000961 LValue BaseLValue =
962 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
963 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000964 // Store the address of the original variable associated with the LHS
965 // implicit variable.
966 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
967 return OASELValueLB.getAddress();
968 });
969 // Emit reduction copy.
970 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000971 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000972 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000973 // Emit VarDecl with copy init for arrays.
974 // Get the address of the original variable captured in current
975 // captured region.
976 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
977 OASELValueLB.getPointer());
978 Size = Builder.CreateNUWAdd(
979 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
980 CodeGenFunction::OpaqueValueMapping OpaqueMap(
981 *this, cast<OpaqueValueExpr>(
982 getContext()
983 .getAsVariableArrayType(PrivateVD->getType())
984 ->getSizeExpr()),
985 RValue::get(Size));
986 EmitVariablyModifiedType(PrivateVD->getType());
987 auto Emission = EmitAutoVarAlloca(*PrivateVD);
988 auto Addr = Emission.getAllocatedAddress();
989 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000990 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
991 DRD ? *IRed : Init,
992 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000993 EmitAutoVarCleanups(Emission);
994 // Emit private VarDecl with reduction init.
995 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
996 OASELValueLB.getPointer());
997 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000998 return castToBase(*this, OrigVD->getType(),
999 OASELValueLB.getType(), OriginalBaseLValue,
1000 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001001 });
1002 assert(IsRegistered && "private var already registered as private");
1003 // Silence the warning about unused variable.
1004 (void)IsRegistered;
1005 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1006 return GetAddrOfLocalVar(PrivateVD);
1007 });
1008 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1009 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1010 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1011 Base = TempASE->getBase()->IgnoreParenImpCasts();
1012 auto *DE = cast<DeclRefExpr>(Base);
1013 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1014 auto ASELValue = EmitLValue(ASE);
1015 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001016 LValue BaseLValue = loadToBegin(
1017 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001018 // Store the address of the original variable associated with the LHS
1019 // implicit variable.
1020 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
1021 return ASELValue.getAddress();
1022 });
1023 // Emit reduction copy.
1024 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001025 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001026 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001027 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001028 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1029 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001030 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001031 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1032 ASELValue.getAddress(),
1033 ASELValue.getType());
1034 } else
1035 EmitAutoVarInit(Emission);
1036 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001037 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1038 ASELValue.getPointer());
1039 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001040 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1041 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001042 });
1043 assert(IsRegistered && "private var already registered as private");
1044 // Silence the warning about unused variable.
1045 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001046 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1047 return Builder.CreateElementBitCast(
1048 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1049 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001050 });
1051 } else {
1052 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001053 QualType Type = PrivateVD->getType();
1054 if (getContext().getAsArrayType(Type)) {
1055 // Store the address of the original variable associated with the LHS
1056 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001057 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1058 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1059 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001060 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001061 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001062 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001063 OriginalAddr = Builder.CreateElementBitCast(
1064 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1065 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001066 });
1067 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1068 if (Type->isVariablyModifiedType()) {
1069 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1070 *this, cast<OpaqueValueExpr>(
1071 getContext()
1072 .getAsVariableArrayType(PrivateVD->getType())
1073 ->getSizeExpr()),
1074 RValue::get(
1075 getTypeSize(OrigVD->getType().getNonReferenceType())));
1076 EmitVariablyModifiedType(Type);
1077 }
1078 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1079 auto Addr = Emission.getAllocatedAddress();
1080 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001081 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1082 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001083 EmitAutoVarCleanups(Emission);
1084 return Emission.getAllocatedAddress();
1085 });
1086 assert(IsRegistered && "private var already registered as private");
1087 // Silence the warning about unused variable.
1088 (void)IsRegistered;
1089 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1090 return Builder.CreateElementBitCast(
1091 GetAddrOfLocalVar(PrivateVD),
1092 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1093 });
1094 } else {
1095 // Store the address of the original variable associated with the LHS
1096 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001097 Address OriginalAddr = Address::invalid();
1098 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1099 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001100 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1101 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1102 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001103 OriginalAddr = EmitLValue(&DRE).getAddress();
1104 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001105 });
1106 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001107 bool IsRegistered = PrivateScope.addPrivate(
1108 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001109 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001110 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1111 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001112 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001113 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1114 OriginalAddr,
1115 PrivateVD->getType());
1116 } else
1117 EmitAutoVarInit(Emission);
1118 EmitAutoVarCleanups(Emission);
1119 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001120 });
1121 assert(IsRegistered && "private var already registered as private");
1122 // Silence the warning about unused variable.
1123 (void)IsRegistered;
1124 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1125 return GetAddrOfLocalVar(PrivateVD);
1126 });
1127 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001128 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001129 ++ILHS;
1130 ++IRHS;
1131 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001132 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001133 }
1134 }
1135}
1136
1137void CodeGenFunction::EmitOMPReductionClauseFinal(
1138 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001139 if (!HaveInsertPoint())
1140 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001141 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001142 llvm::SmallVector<const Expr *, 8> LHSExprs;
1143 llvm::SmallVector<const Expr *, 8> RHSExprs;
1144 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001145 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001146 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001147 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001148 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001149 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1150 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1151 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1152 }
1153 if (HasAtLeastOneReduction) {
1154 // Emit nowait reduction if nowait clause is present or directive is a
1155 // parallel directive (it always has implicit barrier).
1156 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001157 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001158 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001159 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1160 D.getDirectiveKind() == OMPD_simd,
1161 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001162 }
1163}
1164
Alexey Bataev61205072016-03-02 04:57:40 +00001165static void emitPostUpdateForReductionClause(
1166 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1167 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1168 if (!CGF.HaveInsertPoint())
1169 return;
1170 llvm::BasicBlock *DoneBB = nullptr;
1171 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1172 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1173 if (!DoneBB) {
1174 if (auto *Cond = CondGen(CGF)) {
1175 // If the first post-update expression is found, emit conditional
1176 // block if it was requested.
1177 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1178 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1179 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1180 CGF.EmitBlock(ThenBB);
1181 }
1182 }
1183 CGF.EmitIgnoredExpr(PostUpdate);
1184 }
1185 }
1186 if (DoneBB)
1187 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1188}
1189
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1191 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001192 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001193 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001194 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001195 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1196 emitParallelOrTeamsOutlinedFunction(S,
1197 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001198 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001199 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001200 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1201 /*IgnoreResultAssign*/ true);
1202 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1203 CGF, NumThreads, NumThreadsClause->getLocStart());
1204 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001205 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001206 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001207 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1208 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1209 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001210 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001211 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1212 if (C->getNameModifier() == OMPD_unknown ||
1213 C->getNameModifier() == OMPD_parallel) {
1214 IfCond = C->getCondition();
1215 break;
1216 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001217 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001218
1219 OMPLexicalScope Scope(CGF, S);
1220 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1221 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001222 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001223 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001224}
1225
1226void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001227 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001228 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001229 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001230 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001231 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1232 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001233 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001234 // propagation master's thread values of threadprivate variables to local
1235 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001236 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1237 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1238 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001239 }
1240 CGF.EmitOMPPrivateClause(S, PrivateScope);
1241 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1242 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001243 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001244 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001246 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001247 emitPostUpdateForReductionClause(
1248 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001249}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001250
Alexey Bataev0f34da12015-07-02 04:17:07 +00001251void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1252 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001253 RunCleanupsScope BodyScope(*this);
1254 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001255 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001256 EmitIgnoredExpr(I);
1257 }
Alexander Musman3276a272015-03-21 10:12:56 +00001258 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001259 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001260 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001261 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001262 }
1263
Alexander Musmana5f070a2014-10-01 06:03:56 +00001264 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001265 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001266 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001267 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001268 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001269 // The end (updates/cleanups).
1270 EmitBlock(Continue.getBlock());
1271 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001272}
1273
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001274void CodeGenFunction::EmitOMPInnerLoop(
1275 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1276 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001277 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1278 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001279 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001280
1281 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001282 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283 EmitBlock(CondBlock);
Hal Finkelc07e19b2016-05-25 21:53:24 +00001284 LoopStack.push(CondBlock, Builder.getCurrentDebugLocation());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001285
1286 // If there are any cleanups between here and the loop-exit scope,
1287 // create a block to stage a loop exit along.
1288 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001289 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001290 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001291
Alexander Musmand196ef22014-10-07 08:57:09 +00001292 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001293
Alexey Bataev2df54a02015-03-12 08:53:29 +00001294 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001295 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001296 if (ExitBlock != LoopExit.getBlock()) {
1297 EmitBlock(ExitBlock);
1298 EmitBranchThroughCleanup(LoopExit);
1299 }
1300
1301 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001302 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001303
1304 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001305 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1307
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001308 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309
1310 // Emit "IV = IV + 1" and a back-edge to the condition block.
1311 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001312 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001313 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314 BreakContinueStack.pop_back();
1315 EmitBranch(CondBlock);
1316 LoopStack.pop();
1317 // Emit the fall-through block.
1318 EmitBlock(LoopExit.getBlock());
1319}
1320
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001321void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001322 if (!HaveInsertPoint())
1323 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001324 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001325 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001326 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001327 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001328 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1329 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1330 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1331 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1332 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1333 VD->getInit()->getType(), VK_LValue,
1334 VD->getInit()->getExprLoc());
1335 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1336 VD->getType()),
1337 /*capturedByInit=*/false);
1338 EmitAutoVarCleanups(Emission);
1339 } else
1340 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001341 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001342 // Emit the linear steps for the linear clauses.
1343 // If a step is not constant, it is pre-calculated before the loop.
1344 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1345 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001346 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001347 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001348 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001349 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001350 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001351}
1352
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001353void CodeGenFunction::EmitOMPLinearClauseFinal(
1354 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001355 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001356 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001357 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001358 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001359 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001360 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001361 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001362 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001363 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001364 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001365 // If the first post-update expression is found, emit conditional
1366 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001367 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1368 DoneBB = createBasicBlock(".omp.linear.pu.done");
1369 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1370 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001371 }
1372 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001373 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1374 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001375 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001376 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001377 Address OrigAddr = EmitLValue(&DRE).getAddress();
1378 CodeGenFunction::OMPPrivateScope VarScope(*this);
1379 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001380 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001381 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001382 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001383 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001384 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001385 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001386 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001387 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001388 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001389}
1390
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001391static void emitAlignedClause(CodeGenFunction &CGF,
1392 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001393 if (!CGF.HaveInsertPoint())
1394 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001395 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001396 unsigned ClauseAlignment = 0;
1397 if (auto AlignmentExpr = Clause->getAlignment()) {
1398 auto AlignmentCI =
1399 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1400 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001401 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001402 for (auto E : Clause->varlists()) {
1403 unsigned Alignment = ClauseAlignment;
1404 if (Alignment == 0) {
1405 // OpenMP [2.8.1, Description]
1406 // If no optional parameter is specified, implementation-defined default
1407 // alignments for SIMD instructions on the target platforms are assumed.
1408 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001409 CGF.getContext()
1410 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1411 E->getType()->getPointeeType()))
1412 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001413 }
1414 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1415 "alignment is not power of 2");
1416 if (Alignment != 0) {
1417 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1418 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1419 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001420 }
1421 }
1422}
1423
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424void CodeGenFunction::EmitOMPPrivateLoopCounters(
1425 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1426 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001427 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001428 auto I = S.private_counters().begin();
1429 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001430 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1431 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001432 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001433 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001434 if (!LocalDeclMap.count(PrivateVD)) {
1435 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1436 EmitAutoVarCleanups(VarEmission);
1437 }
1438 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1439 /*RefersToEnclosingVariableOrCapture=*/false,
1440 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1441 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001442 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001443 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1444 VD->hasGlobalStorage()) {
1445 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1446 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1447 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1448 E->getType(), VK_LValue, E->getExprLoc());
1449 return EmitLValue(&DRE).getAddress();
1450 });
1451 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001452 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001453 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001454}
1455
Alexey Bataev62dbb972015-04-22 11:59:37 +00001456static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1457 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1458 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001459 if (!CGF.HaveInsertPoint())
1460 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001461 {
1462 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001463 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001464 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001465 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001466 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001467 CGF.EmitIgnoredExpr(I);
1468 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001469 }
1470 // Check that loop is executed at least one time.
1471 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1472}
1473
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001474void CodeGenFunction::EmitOMPLinearClause(
1475 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1476 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001477 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1479 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1480 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1481 for (auto *C : LoopDirective->counters()) {
1482 SIMDLCVs.insert(
1483 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1484 }
1485 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001486 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001487 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001488 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001489 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1490 auto *PrivateVD =
1491 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001492 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1493 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1494 // Emit private VarDecl with copy init.
1495 EmitVarDecl(*PrivateVD);
1496 return GetAddrOfLocalVar(PrivateVD);
1497 });
1498 assert(IsRegistered && "linear var already registered as private");
1499 // Silence the warning about unused variable.
1500 (void)IsRegistered;
1501 } else
1502 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001503 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001504 }
1505 }
1506}
1507
Alexey Bataev45bfad52015-08-21 12:19:04 +00001508static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001509 const OMPExecutableDirective &D,
1510 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001511 if (!CGF.HaveInsertPoint())
1512 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001513 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001514 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1515 /*ignoreResult=*/true);
1516 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1517 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1518 // In presence of finite 'safelen', it may be unsafe to mark all
1519 // the memory instructions parallel, because loop-carried
1520 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001521 if (!IsMonotonic)
1522 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001523 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001524 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1525 /*ignoreResult=*/true);
1526 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001527 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001528 // In presence of finite 'safelen', it may be unsafe to mark all
1529 // the memory instructions parallel, because loop-carried
1530 // dependences of 'safelen' iterations are possible.
1531 CGF.LoopStack.setParallel(false);
1532 }
1533}
1534
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001535void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1536 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001537 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001538 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001539 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001540 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001541}
1542
Alexey Bataevef549a82016-03-09 09:49:09 +00001543void CodeGenFunction::EmitOMPSimdFinal(
1544 const OMPLoopDirective &D,
1545 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001546 if (!HaveInsertPoint())
1547 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001548 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001549 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001550 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001551 for (auto F : D.finals()) {
1552 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001553 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1554 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1555 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1556 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001557 if (!DoneBB) {
1558 if (auto *Cond = CondGen(*this)) {
1559 // If the first post-update expression is found, emit conditional
1560 // block if it was requested.
1561 auto *ThenBB = createBasicBlock(".omp.final.then");
1562 DoneBB = createBasicBlock(".omp.final.done");
1563 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1564 EmitBlock(ThenBB);
1565 }
1566 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001567 Address OrigAddr = Address::invalid();
1568 if (CED)
1569 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1570 else {
1571 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1572 /*RefersToEnclosingVariableOrCapture=*/false,
1573 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1574 OrigAddr = EmitLValue(&DRE).getAddress();
1575 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001576 OMPPrivateScope VarScope(*this);
1577 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001578 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001579 (void)VarScope.Privatize();
1580 EmitIgnoredExpr(F);
1581 }
1582 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001583 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001584 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001585 if (DoneBB)
1586 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001587}
1588
Alexander Musman515ad8c2014-05-22 08:54:05 +00001589void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001590 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001591 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001592 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001593 // for (IV in 0..LastIteration) BODY;
1594 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001595 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001596 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001597
Alexey Bataev62dbb972015-04-22 11:59:37 +00001598 // Emit: if (PreCond) - begin.
1599 // If the condition constant folds and can be elided, avoid emitting the
1600 // whole loop.
1601 bool CondConstant;
1602 llvm::BasicBlock *ContBlock = nullptr;
1603 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1604 if (!CondConstant)
1605 return;
1606 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001607 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1608 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001609 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1610 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001611 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001612 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001613 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001614
1615 // Emit the loop iteration variable.
1616 const Expr *IVExpr = S.getIterationVariable();
1617 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1618 CGF.EmitVarDecl(*IVDecl);
1619 CGF.EmitIgnoredExpr(S.getInit());
1620
1621 // Emit the iterations count variable.
1622 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001623 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001624 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1625 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1626 // Emit calculation of the iterations count.
1627 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001628 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001629
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001630 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001631
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001633 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001634 {
1635 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001636 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1637 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001638 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001639 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001640 bool HasLastprivateClause =
1641 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001642 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001643 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1644 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001645 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001646 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001647 CGF.EmitStopPoint(&S);
1648 },
1649 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001650 CGF.EmitOMPSimdFinal(
1651 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001652 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001653 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001654 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001655 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001656 emitPostUpdateForReductionClause(
1657 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001658 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001659 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001660 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001661 // Emit: if (PreCond) - end.
1662 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001663 CGF.EmitBranch(ContBlock);
1664 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001665 }
1666 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001667 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001668 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001669}
1670
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001671void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001672 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1673 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001674 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001675
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001676 const Expr *IVExpr = S.getIterationVariable();
1677 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1678 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1679
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001680 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1681
1682 // Start the loop with a block that tests the condition.
1683 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1684 EmitBlock(CondBlock);
Hal Finkelc07e19b2016-05-25 21:53:24 +00001685 LoopStack.push(CondBlock, Builder.getCurrentDebugLocation());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001686
1687 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001688 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001689 // UB = min(UB, GlobalUB)
1690 EmitIgnoredExpr(S.getEnsureUpperBound());
1691 // IV = LB
1692 EmitIgnoredExpr(S.getInit());
1693 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001694 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001695 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001696 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1697 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001698 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001699
1700 // If there are any cleanups between here and the loop-exit scope,
1701 // create a block to stage a loop exit along.
1702 auto ExitBlock = LoopExit.getBlock();
1703 if (LoopScope.requiresCleanups())
1704 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1705
1706 auto LoopBody = createBasicBlock("omp.dispatch.body");
1707 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1708 if (ExitBlock != LoopExit.getBlock()) {
1709 EmitBlock(ExitBlock);
1710 EmitBranchThroughCleanup(LoopExit);
1711 }
1712 EmitBlock(LoopBody);
1713
Alexander Musman92bdaab2015-03-12 13:37:50 +00001714 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1715 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001716 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001717 EmitIgnoredExpr(S.getInit());
1718
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001719 // Create a block for the increment.
1720 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1721 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1722
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001723 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1724 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001725 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1726 LoopStack.setParallel(!IsMonotonic);
1727 else
1728 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001729
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001730 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001731 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1732 [&S, LoopExit](CodeGenFunction &CGF) {
1733 CGF.EmitOMPLoopBody(S, LoopExit);
1734 CGF.EmitStopPoint(&S);
1735 },
1736 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1737 if (Ordered) {
1738 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1739 CGF, Loc, IVSize, IVSigned);
1740 }
1741 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001742
1743 EmitBlock(Continue.getBlock());
1744 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001745 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001746 // Emit "LB = LB + Stride", "UB = UB + Stride".
1747 EmitIgnoredExpr(S.getNextLowerBound());
1748 EmitIgnoredExpr(S.getNextUpperBound());
1749 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001750
1751 EmitBranch(CondBlock);
1752 LoopStack.pop();
1753 // Emit the fall-through block.
1754 EmitBlock(LoopExit.getBlock());
1755
1756 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001757 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001758 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001759
1760}
1761
1762void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001763 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001764 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1765 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1766 auto &RT = CGM.getOpenMPRuntime();
1767
1768 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001769 const bool DynamicOrOrdered =
1770 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001771
1772 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001773 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1774 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001775 "static non-chunked schedule does not need outer loop");
1776
1777 // Emit outer loop.
1778 //
1779 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1780 // When schedule(dynamic,chunk_size) is specified, the iterations are
1781 // distributed to threads in the team in chunks as the threads request them.
1782 // Each thread executes a chunk of iterations, then requests another chunk,
1783 // until no chunks remain to be distributed. Each chunk contains chunk_size
1784 // iterations, except for the last chunk to be distributed, which may have
1785 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1786 //
1787 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1788 // to threads in the team in chunks as the executing threads request them.
1789 // Each thread executes a chunk of iterations, then requests another chunk,
1790 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1791 // each chunk is proportional to the number of unassigned iterations divided
1792 // by the number of threads in the team, decreasing to 1. For a chunk_size
1793 // with value k (greater than 1), the size of each chunk is determined in the
1794 // same way, with the restriction that the chunks do not contain fewer than k
1795 // iterations (except for the last chunk to be assigned, which may have fewer
1796 // than k iterations).
1797 //
1798 // When schedule(auto) is specified, the decision regarding scheduling is
1799 // delegated to the compiler and/or runtime system. The programmer gives the
1800 // implementation the freedom to choose any possible mapping of iterations to
1801 // threads in the team.
1802 //
1803 // When schedule(runtime) is specified, the decision regarding scheduling is
1804 // deferred until run time, and the schedule and chunk size are taken from the
1805 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1806 // implementation defined
1807 //
1808 // while(__kmpc_dispatch_next(&LB, &UB)) {
1809 // idx = LB;
1810 // while (idx <= UB) { BODY; ++idx;
1811 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1812 // } // inner loop
1813 // }
1814 //
1815 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1816 // When schedule(static, chunk_size) is specified, iterations are divided into
1817 // chunks of size chunk_size, and the chunks are assigned to the threads in
1818 // the team in a round-robin fashion in the order of the thread number.
1819 //
1820 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1821 // while (idx <= UB) { BODY; ++idx; } // inner loop
1822 // LB = LB + ST;
1823 // UB = UB + ST;
1824 // }
1825 //
1826
1827 const Expr *IVExpr = S.getIterationVariable();
1828 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1829 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1830
1831 if (DynamicOrOrdered) {
1832 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001833 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1834 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001835 } else {
1836 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1837 Ordered, IL, LB, UB, ST, Chunk);
1838 }
1839
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001840 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001841 ST, IL, Chunk);
1842}
1843
1844void CodeGenFunction::EmitOMPDistributeOuterLoop(
1845 OpenMPDistScheduleClauseKind ScheduleKind,
1846 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1847 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1848
1849 auto &RT = CGM.getOpenMPRuntime();
1850
1851 // Emit outer loop.
1852 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1853 // dynamic
1854 //
1855
1856 const Expr *IVExpr = S.getIterationVariable();
1857 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1858 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1859
1860 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1861 IVSize, IVSigned, /* Ordered = */ false,
1862 IL, LB, UB, ST, Chunk);
1863
1864 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1865 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001866}
1867
Carlo Bertolli9925f152016-06-27 14:55:37 +00001868void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1869 const OMPDistributeParallelForDirective &S) {
1870 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1871 CGM.getOpenMPRuntime().emitInlinedDirective(
1872 *this, OMPD_distribute_parallel_for,
1873 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1874 OMPLoopScope PreInitScope(CGF, S);
1875 CGF.EmitStmt(
1876 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1877 });
1878}
1879
Kelvin Li4a39add2016-07-05 05:00:15 +00001880void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1881 const OMPDistributeParallelForSimdDirective &S) {
1882 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1883 CGM.getOpenMPRuntime().emitInlinedDirective(
1884 *this, OMPD_distribute_parallel_for_simd,
1885 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1886 OMPLoopScope PreInitScope(CGF, S);
1887 CGF.EmitStmt(
1888 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1889 });
1890}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001891
1892void CodeGenFunction::EmitOMPDistributeSimdDirective(
1893 const OMPDistributeSimdDirective &S) {
1894 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1895 CGM.getOpenMPRuntime().emitInlinedDirective(
1896 *this, OMPD_distribute_simd,
1897 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1898 OMPLoopScope PreInitScope(CGF, S);
1899 CGF.EmitStmt(
1900 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1901 });
1902}
1903
Alexander Musmanc6388682014-12-15 07:07:06 +00001904/// \brief Emit a helper variable and return corresponding lvalue.
1905static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1906 const DeclRefExpr *Helper) {
1907 auto VDecl = cast<VarDecl>(Helper->getDecl());
1908 CGF.EmitVarDecl(*VDecl);
1909 return CGF.EmitLValue(Helper);
1910}
1911
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001912namespace {
1913 struct ScheduleKindModifiersTy {
1914 OpenMPScheduleClauseKind Kind;
1915 OpenMPScheduleClauseModifier M1;
1916 OpenMPScheduleClauseModifier M2;
1917 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1918 OpenMPScheduleClauseModifier M1,
1919 OpenMPScheduleClauseModifier M2)
1920 : Kind(Kind), M1(M1), M2(M2) {}
1921 };
1922} // namespace
1923
Alexey Bataev38e89532015-04-16 04:54:05 +00001924bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001925 // Emit the loop iteration variable.
1926 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1927 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1928 EmitVarDecl(*IVDecl);
1929
1930 // Emit the iterations count variable.
1931 // If it is not a variable, Sema decided to calculate iterations count on each
1932 // iteration (e.g., it is foldable into a constant).
1933 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1934 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1935 // Emit calculation of the iterations count.
1936 EmitIgnoredExpr(S.getCalcLastIteration());
1937 }
1938
1939 auto &RT = CGM.getOpenMPRuntime();
1940
Alexey Bataev38e89532015-04-16 04:54:05 +00001941 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001942 // Check pre-condition.
1943 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001944 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001945 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001946 // If the condition constant folds and can be elided, avoid emitting the
1947 // whole loop.
1948 bool CondConstant;
1949 llvm::BasicBlock *ContBlock = nullptr;
1950 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1951 if (!CondConstant)
1952 return false;
1953 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001954 auto *ThenBlock = createBasicBlock("omp.precond.then");
1955 ContBlock = createBasicBlock("omp.precond.end");
1956 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001957 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001958 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001959 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001960 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001961
Alexey Bataev8b427062016-05-25 12:36:08 +00001962 bool Ordered = false;
1963 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
1964 if (OrderedClause->getNumForLoops())
1965 RT.emitDoacrossInit(*this, S);
1966 else
1967 Ordered = true;
1968 }
1969
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001970 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001971 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001972 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001973 // Emit helper vars inits.
1974 LValue LB =
1975 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1976 LValue UB =
1977 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1978 LValue ST =
1979 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1980 LValue IL =
1981 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1982
Alexander Musmanc6388682014-12-15 07:07:06 +00001983 // Emit 'then' code.
1984 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001985 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001986 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1987 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001988 // initialization of firstprivate variables and post-update of
1989 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001990 CGM.getOpenMPRuntime().emitBarrierCall(
1991 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1992 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001993 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001994 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001995 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001996 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001997 EmitOMPPrivateLoopCounters(S, LoopScope);
1998 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001999 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002000
2001 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002002 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002003 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002004 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002005 ScheduleKind.Schedule = C->getScheduleKind();
2006 ScheduleKind.M1 = C->getFirstScheduleModifier();
2007 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002008 if (const auto *Ch = C->getChunkSize()) {
2009 Chunk = EmitScalarExpr(Ch);
2010 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2011 S.getIterationVariable()->getType(),
2012 S.getLocStart());
2013 }
2014 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002015 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2016 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002017 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2018 // If the static schedule kind is specified or if the ordered clause is
2019 // specified, and if no monotonic modifier is specified, the effect will
2020 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002021 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002022 /* Chunked */ Chunk != nullptr) &&
2023 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002024 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2025 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002026 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2027 // When no chunk_size is specified, the iteration space is divided into
2028 // chunks that are approximately equal in size, and at most one chunk is
2029 // distributed to each thread. Note that the size of the chunks is
2030 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002031 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2032 IVSize, IVSigned, Ordered,
2033 IL.getAddress(), LB.getAddress(),
2034 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002035 auto LoopExit =
2036 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002037 // UB = min(UB, GlobalUB);
2038 EmitIgnoredExpr(S.getEnsureUpperBound());
2039 // IV = LB;
2040 EmitIgnoredExpr(S.getInit());
2041 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002042 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2043 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002044 [&S, LoopExit](CodeGenFunction &CGF) {
2045 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002046 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002047 },
2048 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002049 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002050 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002051 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002052 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002053 const bool IsMonotonic =
2054 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2055 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2056 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2057 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002058 // Emit the outer loop, which requests its work chunk [LB..UB] from
2059 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002060 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002061 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2062 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002063 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002064 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2065 EmitOMPSimdFinal(S,
2066 [&](CodeGenFunction &CGF) -> llvm::Value * {
2067 return CGF.Builder.CreateIsNotNull(
2068 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2069 });
2070 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002071 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002072 // Emit post-update of the reduction variables if IsLastIter != 0.
2073 emitPostUpdateForReductionClause(
2074 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2075 return CGF.Builder.CreateIsNotNull(
2076 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2077 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002078 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2079 if (HasLastprivateClause)
2080 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002081 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2082 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002083 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002084 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002085 return CGF.Builder.CreateIsNotNull(
2086 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2087 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002088 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002089 if (ContBlock) {
2090 EmitBranch(ContBlock);
2091 EmitBlock(ContBlock, true);
2092 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002093 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002094 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002095}
2096
2097void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002098 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002099 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2100 PrePostActionTy &) {
2101 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2102 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002103 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002104 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002105 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2106 S.hasCancel());
2107 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002108
2109 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002110 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002111 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2112 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002113}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002114
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002115void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002116 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002117 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2118 PrePostActionTy &) {
2119 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2120 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002121 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002122 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002123 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2124 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002125
2126 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002127 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002128 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2129 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002130}
2131
Alexey Bataev2df54a02015-03-12 08:53:29 +00002132static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2133 const Twine &Name,
2134 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002135 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002136 if (Init)
2137 CGF.EmitScalarInit(Init, LVal);
2138 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002139}
2140
Alexey Bataev3392d762016-02-16 11:18:12 +00002141void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002142 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2143 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002144 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002145 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2146 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002147 auto &C = CGF.CGM.getContext();
2148 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2149 // Emit helper vars inits.
2150 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2151 CGF.Builder.getInt32(0));
2152 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2153 : CGF.Builder.getInt32(0);
2154 LValue UB =
2155 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2156 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2157 CGF.Builder.getInt32(1));
2158 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2159 CGF.Builder.getInt32(0));
2160 // Loop counter.
2161 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2162 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2163 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2164 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2165 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2166 // Generate condition for loop.
2167 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2168 OK_Ordinary, S.getLocStart(),
2169 /*fpContractable=*/false);
2170 // Increment for loop counter.
2171 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2172 S.getLocStart());
2173 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2174 // Iterate through all sections and emit a switch construct:
2175 // switch (IV) {
2176 // case 0:
2177 // <SectionStmt[0]>;
2178 // break;
2179 // ...
2180 // case <NumSection> - 1:
2181 // <SectionStmt[<NumSection> - 1]>;
2182 // break;
2183 // }
2184 // .omp.sections.exit:
2185 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2186 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2187 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2188 CS == nullptr ? 1 : CS->size());
2189 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002190 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002191 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002192 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2193 CGF.EmitBlock(CaseBB);
2194 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002195 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002196 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002197 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002198 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002199 } else {
2200 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2201 CGF.EmitBlock(CaseBB);
2202 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2203 CGF.EmitStmt(Stmt);
2204 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002205 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002206 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002207 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002208
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002209 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2210 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002211 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002212 // initialization of firstprivate variables and post-update of lastprivate
2213 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002214 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2215 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2216 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002217 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002218 CGF.EmitOMPPrivateClause(S, LoopScope);
2219 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2220 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2221 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002222
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002223 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002224 OpenMPScheduleTy ScheduleKind;
2225 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002226 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002227 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002228 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2229 UB.getAddress(), ST.getAddress());
2230 // UB = min(UB, GlobalUB);
2231 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2232 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2233 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2234 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2235 // IV = LB;
2236 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2237 // while (idx <= UB) { BODY; ++idx; }
2238 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2239 [](CodeGenFunction &) {});
2240 // Tell the runtime we are done.
2241 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2242 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002243 // Emit post-update of the reduction variables if IsLastIter != 0.
2244 emitPostUpdateForReductionClause(
2245 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2246 return CGF.Builder.CreateIsNotNull(
2247 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2248 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002249
2250 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2251 if (HasLastprivates)
2252 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002253 S, /*NoFinals=*/false,
2254 CGF.Builder.CreateIsNotNull(
2255 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002256 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002257
2258 bool HasCancel = false;
2259 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2260 HasCancel = OSD->hasCancel();
2261 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2262 HasCancel = OPSD->hasCancel();
2263 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2264 HasCancel);
2265 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2266 // clause. Otherwise the barrier will be generated by the codegen for the
2267 // directive.
2268 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002269 // Emit implicit barrier to synchronize threads and avoid data races on
2270 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002271 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2272 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002273 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002274}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002275
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002276void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002277 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002278 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002279 EmitSections(S);
2280 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002281 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002282 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002283 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2284 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002285 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002286}
2287
2288void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002289 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002290 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002291 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002292 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002293 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2294 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002295}
2296
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002297void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002298 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002299 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002300 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002301 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002302 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002303 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002304 // Build a list of copyprivate variables along with helper expressions
2305 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002306 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002307 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002308 DestExprs.append(C->destination_exprs().begin(),
2309 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002310 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002311 AssignmentOps.append(C->assignment_ops().begin(),
2312 C->assignment_ops().end());
2313 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002314 // Emit code for 'single' region along with 'copyprivate' clauses
2315 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2316 Action.Enter(CGF);
2317 OMPPrivateScope SingleScope(CGF);
2318 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2319 CGF.EmitOMPPrivateClause(S, SingleScope);
2320 (void)SingleScope.Privatize();
2321 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2322 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002323 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002324 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002325 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2326 CopyprivateVars, DestExprs,
2327 SrcExprs, AssignmentOps);
2328 }
2329 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2330 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002331 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002332 CGM.getOpenMPRuntime().emitBarrierCall(
2333 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002334 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002335 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002336}
2337
Alexey Bataev8d690652014-12-04 07:23:53 +00002338void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002339 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2340 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002341 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002342 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002343 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002344 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002345}
2346
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002347void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002348 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2349 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002350 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002351 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002352 Expr *Hint = nullptr;
2353 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2354 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002355 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002356 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2357 S.getDirectiveName().getAsString(),
2358 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002359}
2360
Alexey Bataev671605e2015-04-13 05:28:11 +00002361void CodeGenFunction::EmitOMPParallelForDirective(
2362 const OMPParallelForDirective &S) {
2363 // Emit directive as a combined directive that consists of two implicit
2364 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002365 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002366 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002367 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002368 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002369}
2370
Alexander Musmane4e893b2014-09-23 09:33:00 +00002371void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002372 const OMPParallelForSimdDirective &S) {
2373 // Emit directive as a combined directive that consists of two implicit
2374 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002375 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002376 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002377 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002378 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002379}
2380
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002381void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002382 const OMPParallelSectionsDirective &S) {
2383 // Emit directive as a combined directive that consists of two implicit
2384 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002385 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2386 CGF.EmitSections(S);
2387 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002388 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002389}
2390
Alexey Bataev7292c292016-04-25 12:22:29 +00002391void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2392 const RegionCodeGenTy &BodyGen,
2393 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002394 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002395 // Emit outlined function for task construct.
2396 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002397 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002398 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002399 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002400 // Check if the task is final
2401 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2402 // If the condition constant folds and can be elided, try to avoid emitting
2403 // the condition and the dead arm of the if/else.
2404 auto *Cond = Clause->getCondition();
2405 bool CondConstant;
2406 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2407 Data.Final.setInt(CondConstant);
2408 else
2409 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2410 } else {
2411 // By default the task is not final.
2412 Data.Final.setInt(/*IntVal=*/false);
2413 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002414 // Check if the task has 'priority' clause.
2415 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
2416 // Runtime currently does not support codegen for priority clause argument.
2417 // TODO: Add codegen for priority clause arg when runtime lib support it.
2418 auto *Prio = Clause->getPriority();
2419 Data.Priority.setInt(Prio);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002420 Data.Priority.setPointer(EmitScalarConversion(
2421 EmitScalarExpr(Prio), Prio->getType(),
2422 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2423 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002424 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002425 // The first function argument for tasks is a thread id, the second one is a
2426 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002427 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2428 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002429 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002430 auto IRef = C->varlist_begin();
2431 for (auto *IInit : C->private_copies()) {
2432 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2433 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002434 Data.PrivateVars.push_back(*IRef);
2435 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002436 }
2437 ++IRef;
2438 }
2439 }
2440 EmittedAsPrivate.clear();
2441 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002442 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002443 auto IRef = C->varlist_begin();
2444 auto IElemInitRef = C->inits().begin();
2445 for (auto *IInit : C->private_copies()) {
2446 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2447 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002448 Data.FirstprivateVars.push_back(*IRef);
2449 Data.FirstprivateCopies.push_back(IInit);
2450 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002451 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002452 ++IRef;
2453 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002454 }
2455 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002456 // Get list of lastprivate variables (for taskloops).
2457 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2458 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2459 auto IRef = C->varlist_begin();
2460 auto ID = C->destination_exprs().begin();
2461 for (auto *IInit : C->private_copies()) {
2462 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2463 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2464 Data.LastprivateVars.push_back(*IRef);
2465 Data.LastprivateCopies.push_back(IInit);
2466 }
2467 LastprivateDstsOrigs.insert(
2468 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2469 cast<DeclRefExpr>(*IRef)});
2470 ++IRef;
2471 ++ID;
2472 }
2473 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002474 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002475 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2476 for (auto *IRef : C->varlists())
2477 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevf93095a2016-05-05 08:46:22 +00002478 auto &&CodeGen = [PartId, &S, &Data, CS, &BodyGen, &LastprivateDstsOrigs](
2479 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002480 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002481 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002482 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2483 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002484 auto *CopyFn = CGF.Builder.CreateLoad(
2485 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2486 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2487 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2488 // Map privates.
2489 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2490 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2491 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002492 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002493 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2494 Address PrivatePtr = CGF.CreateMemTemp(
2495 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2496 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2497 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002498 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002499 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002500 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2501 Address PrivatePtr =
2502 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2503 ".firstpriv.ptr.addr");
2504 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2505 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002506 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002507 for (auto *E : Data.LastprivateVars) {
2508 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2509 Address PrivatePtr =
2510 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2511 ".lastpriv.ptr.addr");
2512 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2513 CallArgs.push_back(PrivatePtr.getPointer());
2514 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002515 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002516 for (auto &&Pair : LastprivateDstsOrigs) {
2517 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2518 DeclRefExpr DRE(
2519 const_cast<VarDecl *>(OrigVD),
2520 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2521 OrigVD) != nullptr,
2522 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2523 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2524 return CGF.EmitLValue(&DRE).getAddress();
2525 });
2526 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002527 for (auto &&Pair : PrivatePtrs) {
2528 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2529 CGF.getContext().getDeclAlign(Pair.first));
2530 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2531 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002532 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002533 (void)Scope.Privatize();
2534
2535 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002536 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002537 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002538 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2539 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2540 Data.NumberOfParts);
2541 OMPLexicalScope Scope(*this, S);
2542 TaskGen(*this, OutlinedFn, Data);
2543}
2544
2545void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2546 // Emit outlined function for task construct.
2547 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2548 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002549 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002550 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002551 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2552 if (C->getNameModifier() == OMPD_unknown ||
2553 C->getNameModifier() == OMPD_task) {
2554 IfCond = C->getCondition();
2555 break;
2556 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002557 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002558
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002559 OMPTaskDataTy Data;
2560 // Check if we should emit tied or untied task.
2561 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002562 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2563 CGF.EmitStmt(CS->getCapturedStmt());
2564 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002565 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002566 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002567 const OMPTaskDataTy &Data) {
2568 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2569 SharedsTy, CapturedStruct, IfCond,
2570 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002571 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002572 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002573}
2574
Alexey Bataev9f797f32015-02-05 05:57:51 +00002575void CodeGenFunction::EmitOMPTaskyieldDirective(
2576 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002577 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002578}
2579
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002580void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002581 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002582}
2583
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002584void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2585 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002586}
2587
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002588void CodeGenFunction::EmitOMPTaskgroupDirective(
2589 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2591 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002592 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002593 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002594 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002595 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2596}
2597
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002598void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002599 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002600 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002601 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2602 FlushClause->varlist_end());
2603 }
2604 return llvm::None;
2605 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002606}
2607
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002608void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2609 // Emit the loop iteration variable.
2610 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2611 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2612 EmitVarDecl(*IVDecl);
2613
2614 // Emit the iterations count variable.
2615 // If it is not a variable, Sema decided to calculate iterations count on each
2616 // iteration (e.g., it is foldable into a constant).
2617 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2618 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2619 // Emit calculation of the iterations count.
2620 EmitIgnoredExpr(S.getCalcLastIteration());
2621 }
2622
2623 auto &RT = CGM.getOpenMPRuntime();
2624
2625 // Check pre-condition.
2626 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002627 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002628 // Skip the entire loop if we don't meet the precondition.
2629 // If the condition constant folds and can be elided, avoid emitting the
2630 // whole loop.
2631 bool CondConstant;
2632 llvm::BasicBlock *ContBlock = nullptr;
2633 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2634 if (!CondConstant)
2635 return;
2636 } else {
2637 auto *ThenBlock = createBasicBlock("omp.precond.then");
2638 ContBlock = createBasicBlock("omp.precond.end");
2639 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2640 getProfileCount(&S));
2641 EmitBlock(ThenBlock);
2642 incrementProfileCounter(&S);
2643 }
2644
2645 // Emit 'then' code.
2646 {
2647 // Emit helper vars inits.
2648 LValue LB =
2649 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2650 LValue UB =
2651 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2652 LValue ST =
2653 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2654 LValue IL =
2655 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2656
2657 OMPPrivateScope LoopScope(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002658 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002659 (void)LoopScope.Privatize();
2660
2661 // Detect the distribute schedule kind and chunk.
2662 llvm::Value *Chunk = nullptr;
2663 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2664 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2665 ScheduleKind = C->getDistScheduleKind();
2666 if (const auto *Ch = C->getChunkSize()) {
2667 Chunk = EmitScalarExpr(Ch);
2668 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2669 S.getIterationVariable()->getType(),
2670 S.getLocStart());
2671 }
2672 }
2673 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2674 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2675
2676 // OpenMP [2.10.8, distribute Construct, Description]
2677 // If dist_schedule is specified, kind must be static. If specified,
2678 // iterations are divided into chunks of size chunk_size, chunks are
2679 // assigned to the teams of the league in a round-robin fashion in the
2680 // order of the team number. When no chunk_size is specified, the
2681 // iteration space is divided into chunks that are approximately equal
2682 // in size, and at most one chunk is distributed to each team of the
2683 // league. The size of the chunks is unspecified in this case.
2684 if (RT.isStaticNonchunked(ScheduleKind,
2685 /* Chunked */ Chunk != nullptr)) {
2686 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2687 IVSize, IVSigned, /* Ordered = */ false,
2688 IL.getAddress(), LB.getAddress(),
2689 UB.getAddress(), ST.getAddress());
2690 auto LoopExit =
2691 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2692 // UB = min(UB, GlobalUB);
2693 EmitIgnoredExpr(S.getEnsureUpperBound());
2694 // IV = LB;
2695 EmitIgnoredExpr(S.getInit());
2696 // while (idx <= UB) { BODY; ++idx; }
2697 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2698 S.getInc(),
2699 [&S, LoopExit](CodeGenFunction &CGF) {
2700 CGF.EmitOMPLoopBody(S, LoopExit);
2701 CGF.EmitStopPoint(&S);
2702 },
2703 [](CodeGenFunction &) {});
2704 EmitBlock(LoopExit.getBlock());
2705 // Tell the runtime we are done.
2706 RT.emitForStaticFinish(*this, S.getLocStart());
2707 } else {
2708 // Emit the outer loop, which requests its work chunk [LB..UB] from
2709 // runtime and runs the inner loop to process it.
2710 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2711 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2712 IL.getAddress(), Chunk);
2713 }
2714 }
2715
2716 // We're now done with the loop, so jump to the continuation block.
2717 if (ContBlock) {
2718 EmitBranch(ContBlock);
2719 EmitBlock(ContBlock, true);
2720 }
2721 }
2722}
2723
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002724void CodeGenFunction::EmitOMPDistributeDirective(
2725 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002726 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002727 CGF.EmitOMPDistributeLoop(S);
2728 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002729 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002730 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2731 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002732}
2733
Alexey Bataev5f600d62015-09-29 03:48:57 +00002734static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2735 const CapturedStmt *S) {
2736 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2737 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2738 CGF.CapturedStmtInfo = &CapStmtInfo;
2739 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2740 Fn->addFnAttr(llvm::Attribute::NoInline);
2741 return Fn;
2742}
2743
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002744void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002745 if (!S.getAssociatedStmt()) {
2746 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
2747 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00002748 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00002749 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002750 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002751 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2752 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002753 if (C) {
2754 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2755 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2756 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2757 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2758 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2759 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002760 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002761 CGF.EmitStmt(
2762 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2763 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002764 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002765 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002766 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002767}
2768
Alexey Bataevb57056f2015-01-22 06:17:56 +00002769static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002770 QualType SrcType, QualType DestType,
2771 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002772 assert(CGF.hasScalarEvaluationKind(DestType) &&
2773 "DestType must have scalar evaluation kind.");
2774 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2775 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002776 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2777 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002778 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002779 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002780}
2781
2782static CodeGenFunction::ComplexPairTy
2783convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002784 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002785 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2786 "DestType must have complex evaluation kind.");
2787 CodeGenFunction::ComplexPairTy ComplexVal;
2788 if (Val.isScalar()) {
2789 // Convert the input element to the element type of the complex.
2790 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002791 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2792 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002793 ComplexVal = CodeGenFunction::ComplexPairTy(
2794 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2795 } else {
2796 assert(Val.isComplex() && "Must be a scalar or complex.");
2797 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2798 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2799 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002800 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002801 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002802 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002803 }
2804 return ComplexVal;
2805}
2806
Alexey Bataev5e018f92015-04-23 06:35:10 +00002807static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2808 LValue LVal, RValue RVal) {
2809 if (LVal.isGlobalReg()) {
2810 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2811 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002812 CGF.EmitAtomicStore(RVal, LVal,
2813 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2814 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002815 LVal.isVolatile(), /*IsInit=*/false);
2816 }
2817}
2818
Alexey Bataev8524d152016-01-21 12:35:58 +00002819void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2820 QualType RValTy, SourceLocation Loc) {
2821 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002822 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002823 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2824 *this, RVal, RValTy, LVal.getType(), Loc)),
2825 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002826 break;
2827 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002828 EmitStoreOfComplex(
2829 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002830 /*isInit=*/false);
2831 break;
2832 case TEK_Aggregate:
2833 llvm_unreachable("Must be a scalar or complex.");
2834 }
2835}
2836
Alexey Bataevb57056f2015-01-22 06:17:56 +00002837static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2838 const Expr *X, const Expr *V,
2839 SourceLocation Loc) {
2840 // v = x;
2841 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2842 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2843 LValue XLValue = CGF.EmitLValue(X);
2844 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002845 RValue Res = XLValue.isGlobalReg()
2846 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00002847 : CGF.EmitAtomicLoad(
2848 XLValue, Loc,
2849 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2850 : llvm::AtomicOrdering::Monotonic,
2851 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002852 // OpenMP, 2.12.6, atomic Construct
2853 // Any atomic construct with a seq_cst clause forces the atomically
2854 // performed operation to include an implicit flush operation without a
2855 // list.
2856 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002857 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002858 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002859}
2860
Alexey Bataevb8329262015-02-27 06:33:30 +00002861static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2862 const Expr *X, const Expr *E,
2863 SourceLocation Loc) {
2864 // x = expr;
2865 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002866 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002867 // OpenMP, 2.12.6, atomic Construct
2868 // Any atomic construct with a seq_cst clause forces the atomically
2869 // performed operation to include an implicit flush operation without a
2870 // list.
2871 if (IsSeqCst)
2872 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2873}
2874
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002875static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2876 RValue Update,
2877 BinaryOperatorKind BO,
2878 llvm::AtomicOrdering AO,
2879 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002880 auto &Context = CGF.CGM.getContext();
2881 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002882 // expression is simple and atomic is allowed for the given type for the
2883 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002884 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002885 !Update.getScalarVal()->getType()->isIntegerTy() ||
2886 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2887 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002888 X.getAddress().getElementType())) ||
2889 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002890 !Context.getTargetInfo().hasBuiltinAtomic(
2891 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002892 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002893
2894 llvm::AtomicRMWInst::BinOp RMWOp;
2895 switch (BO) {
2896 case BO_Add:
2897 RMWOp = llvm::AtomicRMWInst::Add;
2898 break;
2899 case BO_Sub:
2900 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002901 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002902 RMWOp = llvm::AtomicRMWInst::Sub;
2903 break;
2904 case BO_And:
2905 RMWOp = llvm::AtomicRMWInst::And;
2906 break;
2907 case BO_Or:
2908 RMWOp = llvm::AtomicRMWInst::Or;
2909 break;
2910 case BO_Xor:
2911 RMWOp = llvm::AtomicRMWInst::Xor;
2912 break;
2913 case BO_LT:
2914 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2915 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2916 : llvm::AtomicRMWInst::Max)
2917 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2918 : llvm::AtomicRMWInst::UMax);
2919 break;
2920 case BO_GT:
2921 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2922 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2923 : llvm::AtomicRMWInst::Min)
2924 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2925 : llvm::AtomicRMWInst::UMin);
2926 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002927 case BO_Assign:
2928 RMWOp = llvm::AtomicRMWInst::Xchg;
2929 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002930 case BO_Mul:
2931 case BO_Div:
2932 case BO_Rem:
2933 case BO_Shl:
2934 case BO_Shr:
2935 case BO_LAnd:
2936 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002937 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002938 case BO_PtrMemD:
2939 case BO_PtrMemI:
2940 case BO_LE:
2941 case BO_GE:
2942 case BO_EQ:
2943 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002944 case BO_AddAssign:
2945 case BO_SubAssign:
2946 case BO_AndAssign:
2947 case BO_OrAssign:
2948 case BO_XorAssign:
2949 case BO_MulAssign:
2950 case BO_DivAssign:
2951 case BO_RemAssign:
2952 case BO_ShlAssign:
2953 case BO_ShrAssign:
2954 case BO_Comma:
2955 llvm_unreachable("Unsupported atomic update operation");
2956 }
2957 auto *UpdateVal = Update.getScalarVal();
2958 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2959 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002960 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002961 X.getType()->hasSignedIntegerRepresentation());
2962 }
John McCall7f416cc2015-09-08 08:05:57 +00002963 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002964 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002965}
2966
Alexey Bataev5e018f92015-04-23 06:35:10 +00002967std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002968 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2969 llvm::AtomicOrdering AO, SourceLocation Loc,
2970 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2971 // Update expressions are allowed to have the following forms:
2972 // x binop= expr; -> xrval + expr;
2973 // x++, ++x -> xrval + 1;
2974 // x--, --x -> xrval - 1;
2975 // x = x binop expr; -> xrval binop expr
2976 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002977 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2978 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002979 if (X.isGlobalReg()) {
2980 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2981 // 'xrval'.
2982 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2983 } else {
2984 // Perform compare-and-swap procedure.
2985 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002986 }
2987 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002988 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002989}
2990
2991static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2992 const Expr *X, const Expr *E,
2993 const Expr *UE, bool IsXLHSInRHSPart,
2994 SourceLocation Loc) {
2995 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2996 "Update expr in 'atomic update' must be a binary operator.");
2997 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2998 // Update expressions are allowed to have the following forms:
2999 // x binop= expr; -> xrval + expr;
3000 // x++, ++x -> xrval + 1;
3001 // x--, --x -> xrval - 1;
3002 // x = x binop expr; -> xrval binop expr
3003 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003004 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003005 LValue XLValue = CGF.EmitLValue(X);
3006 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003007 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3008 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003009 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3010 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3011 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3012 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3013 auto Gen =
3014 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3015 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3016 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3017 return CGF.EmitAnyExpr(UE);
3018 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003019 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3020 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3021 // OpenMP, 2.12.6, atomic Construct
3022 // Any atomic construct with a seq_cst clause forces the atomically
3023 // performed operation to include an implicit flush operation without a
3024 // list.
3025 if (IsSeqCst)
3026 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3027}
3028
3029static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003030 QualType SourceType, QualType ResType,
3031 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003032 switch (CGF.getEvaluationKind(ResType)) {
3033 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003034 return RValue::get(
3035 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003036 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003037 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003038 return RValue::getComplex(Res.first, Res.second);
3039 }
3040 case TEK_Aggregate:
3041 break;
3042 }
3043 llvm_unreachable("Must be a scalar or complex.");
3044}
3045
3046static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3047 bool IsPostfixUpdate, const Expr *V,
3048 const Expr *X, const Expr *E,
3049 const Expr *UE, bool IsXLHSInRHSPart,
3050 SourceLocation Loc) {
3051 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3052 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3053 RValue NewVVal;
3054 LValue VLValue = CGF.EmitLValue(V);
3055 LValue XLValue = CGF.EmitLValue(X);
3056 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003057 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3058 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003059 QualType NewVValType;
3060 if (UE) {
3061 // 'x' is updated with some additional value.
3062 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3063 "Update expr in 'atomic capture' must be a binary operator.");
3064 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3065 // Update expressions are allowed to have the following forms:
3066 // x binop= expr; -> xrval + expr;
3067 // x++, ++x -> xrval + 1;
3068 // x--, --x -> xrval - 1;
3069 // x = x binop expr; -> xrval binop expr
3070 // x = expr Op x; - > expr binop xrval;
3071 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3072 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3073 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3074 NewVValType = XRValExpr->getType();
3075 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3076 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
3077 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
3078 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3079 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3080 RValue Res = CGF.EmitAnyExpr(UE);
3081 NewVVal = IsPostfixUpdate ? XRValue : Res;
3082 return Res;
3083 };
3084 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3085 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3086 if (Res.first) {
3087 // 'atomicrmw' instruction was generated.
3088 if (IsPostfixUpdate) {
3089 // Use old value from 'atomicrmw'.
3090 NewVVal = Res.second;
3091 } else {
3092 // 'atomicrmw' does not provide new value, so evaluate it using old
3093 // value of 'x'.
3094 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3095 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3096 NewVVal = CGF.EmitAnyExpr(UE);
3097 }
3098 }
3099 } else {
3100 // 'x' is simply rewritten with some 'expr'.
3101 NewVValType = X->getType().getNonReferenceType();
3102 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003103 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003104 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
3105 NewVVal = XRValue;
3106 return ExprRValue;
3107 };
3108 // Try to perform atomicrmw xchg, otherwise simple exchange.
3109 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3110 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3111 Loc, Gen);
3112 if (Res.first) {
3113 // 'atomicrmw' instruction was generated.
3114 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3115 }
3116 }
3117 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003118 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003119 // OpenMP, 2.12.6, atomic Construct
3120 // Any atomic construct with a seq_cst clause forces the atomically
3121 // performed operation to include an implicit flush operation without a
3122 // list.
3123 if (IsSeqCst)
3124 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3125}
3126
Alexey Bataevb57056f2015-01-22 06:17:56 +00003127static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003128 bool IsSeqCst, bool IsPostfixUpdate,
3129 const Expr *X, const Expr *V, const Expr *E,
3130 const Expr *UE, bool IsXLHSInRHSPart,
3131 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003132 switch (Kind) {
3133 case OMPC_read:
3134 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3135 break;
3136 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003137 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3138 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003139 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003140 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003141 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3142 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003143 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003144 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3145 IsXLHSInRHSPart, Loc);
3146 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003147 case OMPC_if:
3148 case OMPC_final:
3149 case OMPC_num_threads:
3150 case OMPC_private:
3151 case OMPC_firstprivate:
3152 case OMPC_lastprivate:
3153 case OMPC_reduction:
3154 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003155 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003156 case OMPC_collapse:
3157 case OMPC_default:
3158 case OMPC_seq_cst:
3159 case OMPC_shared:
3160 case OMPC_linear:
3161 case OMPC_aligned:
3162 case OMPC_copyin:
3163 case OMPC_copyprivate:
3164 case OMPC_flush:
3165 case OMPC_proc_bind:
3166 case OMPC_schedule:
3167 case OMPC_ordered:
3168 case OMPC_nowait:
3169 case OMPC_untied:
3170 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003171 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003172 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003173 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003174 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003175 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003176 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003177 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003178 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003179 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003180 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003181 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003182 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003183 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003184 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003185 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003186 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003187 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003188 case OMPC_from:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003189 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3190 }
3191}
3192
3193void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003194 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003195 OpenMPClauseKind Kind = OMPC_unknown;
3196 for (auto *C : S.clauses()) {
3197 // Find first clause (skip seq_cst clause, if it is first).
3198 if (C->getClauseKind() != OMPC_seq_cst) {
3199 Kind = C->getClauseKind();
3200 break;
3201 }
3202 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003203
3204 const auto *CS =
3205 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003206 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003207 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003208 }
3209 // Processing for statements under 'atomic capture'.
3210 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3211 for (const auto *C : Compound->body()) {
3212 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3213 enterFullExpression(EWC);
3214 }
3215 }
3216 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003217
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003218 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3219 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003220 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003221 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3222 S.getV(), S.getExpr(), S.getUpdateExpr(),
3223 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003224 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003225 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003226 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003227}
3228
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003229std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
3230CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
3231 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
3232 bool IsOffloadEntry) {
3233 llvm::Function *OutlinedFn = nullptr;
3234 llvm::Constant *OutlinedFnID = nullptr;
3235 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3236 OMPPrivateScope PrivateScope(CGF);
3237 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3238 CGF.EmitOMPPrivateClause(S, PrivateScope);
3239 (void)PrivateScope.Privatize();
3240
3241 Action.Enter(CGF);
3242 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3243 };
3244 // Emit target region as a standalone region.
3245 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3246 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3247 return std::make_pair(OutlinedFn, OutlinedFnID);
3248}
3249
Samuel Antaobed3c462015-10-02 16:14:20 +00003250void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003251 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3252
3253 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003254 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003255
Samuel Antaoee8fb302016-01-06 13:42:12 +00003256 llvm::Function *Fn = nullptr;
3257 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003258
3259 // Check if we have any if clause associated with the directive.
3260 const Expr *IfCond = nullptr;
3261
3262 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3263 IfCond = C->getCondition();
3264 }
3265
3266 // Check if we have any device clause associated with the directive.
3267 const Expr *Device = nullptr;
3268 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3269 Device = C->getDevice();
3270 }
3271
Samuel Antaoee8fb302016-01-06 13:42:12 +00003272 // Check if we have an if clause whose conditional always evaluates to false
3273 // or if we do not have any targets specified. If so the target region is not
3274 // an offload entry point.
3275 bool IsOffloadEntry = true;
3276 if (IfCond) {
3277 bool Val;
3278 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3279 IsOffloadEntry = false;
3280 }
3281 if (CGM.getLangOpts().OMPTargetTriples.empty())
3282 IsOffloadEntry = false;
3283
3284 assert(CurFuncDecl && "No parent declaration for target region!");
3285 StringRef ParentName;
3286 // In case we have Ctors/Dtors we use the complete type variant to produce
3287 // the mangling of the device outlined kernel.
3288 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3289 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3290 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3291 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3292 else
3293 ParentName =
3294 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3295
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003296 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3297 CGM, S, ParentName, IsOffloadEntry);
3298 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003299 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003300 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003301}
3302
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003303static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3304 const OMPExecutableDirective &S,
3305 OpenMPDirectiveKind InnermostKind,
3306 const RegionCodeGenTy &CodeGen) {
3307 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003308 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3309 emitParallelOrTeamsOutlinedFunction(S,
3310 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003311
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003312 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3313 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3314 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3315 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003316 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3317 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003318
Carlo Bertollic6872252016-04-04 15:55:02 +00003319 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3320 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003321 }
3322
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003323 OMPLexicalScope Scope(CGF, S);
3324 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3325 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003326 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3327 CapturedVars);
3328}
3329
3330void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003331 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003332 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003333 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003334 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3335 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003336 (void)PrivateScope.Privatize();
3337 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3338 };
3339 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003340}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003341
3342void CodeGenFunction::EmitOMPCancellationPointDirective(
3343 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003344 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3345 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003346}
3347
Alexey Bataev80909872015-07-02 11:25:17 +00003348void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003349 const Expr *IfCond = nullptr;
3350 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3351 if (C->getNameModifier() == OMPD_unknown ||
3352 C->getNameModifier() == OMPD_cancel) {
3353 IfCond = C->getCondition();
3354 break;
3355 }
3356 }
3357 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003358 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003359}
3360
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003361CodeGenFunction::JumpDest
3362CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3363 if (Kind == OMPD_parallel || Kind == OMPD_task)
3364 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003365 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003366 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003367 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003368}
Michael Wong65f367f2015-07-21 13:44:28 +00003369
3370// Generate the instructions for '#pragma omp target data' directive.
3371void CodeGenFunction::EmitOMPTargetDataDirective(
3372 const OMPTargetDataDirective &S) {
Samuel Antaodf158d52016-04-27 22:58:19 +00003373 // The target data enclosed region is implemented just by emitting the
3374 // statement.
3375 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3376 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3377 };
3378
3379 // If we don't have target devices, don't bother emitting the data mapping
3380 // code.
3381 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
3382 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3383
3384 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_data,
3385 CodeGen);
3386 return;
3387 }
3388
3389 // Check if we have any if clause associated with the directive.
3390 const Expr *IfCond = nullptr;
3391 if (auto *C = S.getSingleClause<OMPIfClause>())
3392 IfCond = C->getCondition();
3393
3394 // Check if we have any device clause associated with the directive.
3395 const Expr *Device = nullptr;
3396 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3397 Device = C->getDevice();
3398
3399 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, CodeGen);
Michael Wong65f367f2015-07-21 13:44:28 +00003400}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003401
Samuel Antaodf67fc42016-01-19 19:15:56 +00003402void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3403 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003404 // If we don't have target devices, don't bother emitting the data mapping
3405 // code.
3406 if (CGM.getLangOpts().OMPTargetTriples.empty())
3407 return;
3408
3409 // Check if we have any if clause associated with the directive.
3410 const Expr *IfCond = nullptr;
3411 if (auto *C = S.getSingleClause<OMPIfClause>())
3412 IfCond = C->getCondition();
3413
3414 // Check if we have any device clause associated with the directive.
3415 const Expr *Device = nullptr;
3416 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3417 Device = C->getDevice();
3418
Samuel Antao8d2d7302016-05-26 18:30:22 +00003419 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003420}
3421
Samuel Antao72590762016-01-19 20:04:50 +00003422void CodeGenFunction::EmitOMPTargetExitDataDirective(
3423 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003424 // If we don't have target devices, don't bother emitting the data mapping
3425 // code.
3426 if (CGM.getLangOpts().OMPTargetTriples.empty())
3427 return;
3428
3429 // Check if we have any if clause associated with the directive.
3430 const Expr *IfCond = nullptr;
3431 if (auto *C = S.getSingleClause<OMPIfClause>())
3432 IfCond = C->getCondition();
3433
3434 // Check if we have any device clause associated with the directive.
3435 const Expr *Device = nullptr;
3436 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3437 Device = C->getDevice();
3438
Samuel Antao8d2d7302016-05-26 18:30:22 +00003439 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003440}
3441
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003442void CodeGenFunction::EmitOMPTargetParallelDirective(
3443 const OMPTargetParallelDirective &S) {
3444 // TODO: codegen for target parallel.
3445}
3446
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003447void CodeGenFunction::EmitOMPTargetParallelForDirective(
3448 const OMPTargetParallelForDirective &S) {
3449 // TODO: codegen for target parallel for.
3450}
3451
Alexey Bataev7292c292016-04-25 12:22:29 +00003452/// Emit a helper variable and return corresponding lvalue.
3453static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3454 const ImplicitParamDecl *PVD,
3455 CodeGenFunction::OMPPrivateScope &Privates) {
3456 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3457 Privates.addPrivate(
3458 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3459}
3460
3461void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3462 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3463 // Emit outlined function for task construct.
3464 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3465 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3466 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3467 const Expr *IfCond = nullptr;
3468 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3469 if (C->getNameModifier() == OMPD_unknown ||
3470 C->getNameModifier() == OMPD_taskloop) {
3471 IfCond = C->getCondition();
3472 break;
3473 }
3474 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003475
3476 OMPTaskDataTy Data;
3477 // Check if taskloop must be emitted without taskgroup.
3478 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003479 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003480 Data.Tied = true;
3481 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003482 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3483 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003484 Data.Schedule.setInt(/*IntVal=*/false);
3485 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003486 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3487 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003488 Data.Schedule.setInt(/*IntVal=*/true);
3489 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003490 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003491
3492 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3493 // if (PreCond) {
3494 // for (IV in 0..LastIteration) BODY;
3495 // <Final counter/linear vars updates>;
3496 // }
3497 //
3498
3499 // Emit: if (PreCond) - begin.
3500 // If the condition constant folds and can be elided, avoid emitting the
3501 // whole loop.
3502 bool CondConstant;
3503 llvm::BasicBlock *ContBlock = nullptr;
3504 OMPLoopScope PreInitScope(CGF, S);
3505 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3506 if (!CondConstant)
3507 return;
3508 } else {
3509 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3510 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3511 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3512 CGF.getProfileCount(&S));
3513 CGF.EmitBlock(ThenBlock);
3514 CGF.incrementProfileCounter(&S);
3515 }
3516
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003517 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3518 CGF.EmitOMPSimdInit(S);
3519
Alexey Bataev7292c292016-04-25 12:22:29 +00003520 OMPPrivateScope LoopScope(CGF);
3521 // Emit helper vars inits.
3522 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3523 auto *I = CS->getCapturedDecl()->param_begin();
3524 auto *LBP = std::next(I, LowerBound);
3525 auto *UBP = std::next(I, UpperBound);
3526 auto *STP = std::next(I, Stride);
3527 auto *LIP = std::next(I, LastIter);
3528 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3529 LoopScope);
3530 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3531 LoopScope);
3532 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3533 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3534 LoopScope);
3535 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003536 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003537 (void)LoopScope.Privatize();
3538 // Emit the loop iteration variable.
3539 const Expr *IVExpr = S.getIterationVariable();
3540 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3541 CGF.EmitVarDecl(*IVDecl);
3542 CGF.EmitIgnoredExpr(S.getInit());
3543
3544 // Emit the iterations count variable.
3545 // If it is not a variable, Sema decided to calculate iterations count on
3546 // each iteration (e.g., it is foldable into a constant).
3547 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3548 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3549 // Emit calculation of the iterations count.
3550 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3551 }
3552
3553 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3554 S.getInc(),
3555 [&S](CodeGenFunction &CGF) {
3556 CGF.EmitOMPLoopBody(S, JumpDest());
3557 CGF.EmitStopPoint(&S);
3558 },
3559 [](CodeGenFunction &) {});
3560 // Emit: if (PreCond) - end.
3561 if (ContBlock) {
3562 CGF.EmitBranch(ContBlock);
3563 CGF.EmitBlock(ContBlock, true);
3564 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003565 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3566 if (HasLastprivateClause) {
3567 CGF.EmitOMPLastprivateClauseFinal(
3568 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3569 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3570 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3571 (*LIP)->getType(), S.getLocStart())));
3572 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003573 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003574 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3575 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3576 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003577 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3578 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003579 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
3580 OutlinedFn, SharedsTy,
3581 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003582 };
3583 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
3584 CodeGen);
3585 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003586 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003587}
3588
Alexey Bataev49f6e782015-12-01 04:18:41 +00003589void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003590 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003591}
3592
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003593void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3594 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003595 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003596}
Samuel Antao686c70c2016-05-26 17:30:50 +00003597
3598// Generate the instructions for '#pragma omp target update' directive.
3599void CodeGenFunction::EmitOMPTargetUpdateDirective(
3600 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00003601 // If we don't have target devices, don't bother emitting the data mapping
3602 // code.
3603 if (CGM.getLangOpts().OMPTargetTriples.empty())
3604 return;
3605
3606 // Check if we have any if clause associated with the directive.
3607 const Expr *IfCond = nullptr;
3608 if (auto *C = S.getSingleClause<OMPIfClause>())
3609 IfCond = C->getCondition();
3610
3611 // Check if we have any device clause associated with the directive.
3612 const Expr *Device = nullptr;
3613 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3614 Device = C->getDevice();
3615
3616 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00003617}