blob: 808af527a399aeab09f793d64c0a2802e78dd6b0 [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 Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
28class OMPLexicalScope {
29 CodeGenFunction::LexicalScope Scope;
30 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
50 : Scope(CGF, S.getSourceRange()) {
51 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
54} // namespace
55
Alexey Bataev1189bd02016-01-26 12:20:39 +000056llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
57 auto &C = getContext();
58 llvm::Value *Size = nullptr;
59 auto SizeInChars = C.getTypeSizeInChars(Ty);
60 if (SizeInChars.isZero()) {
61 // getTypeSizeInChars() returns 0 for a VLA.
62 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
63 llvm::Value *ArraySize;
64 std::tie(ArraySize, Ty) = getVLASize(VAT);
65 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
66 }
67 SizeInChars = C.getTypeSizeInChars(Ty);
68 if (SizeInChars.isZero())
69 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
70 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
71 } else
72 Size = CGM.getSize(SizeInChars);
73 return Size;
74}
75
Alexey Bataev2377fe92015-09-10 08:12:02 +000076void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000077 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000078 const RecordDecl *RD = S.getCapturedRecordDecl();
79 auto CurField = RD->field_begin();
80 auto CurCap = S.captures().begin();
81 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
82 E = S.capture_init_end();
83 I != E; ++I, ++CurField, ++CurCap) {
84 if (CurField->hasCapturedVLAType()) {
85 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000086 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000087 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000088 } else if (CurCap->capturesThis())
89 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000090 else if (CurCap->capturesVariableByCopy())
91 CapturedVars.push_back(
92 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
93 else {
94 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000096 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000097 }
98}
99
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000100static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
101 StringRef Name, LValue AddrLV,
102 bool isReferenceType = false) {
103 ASTContext &Ctx = CGF.getContext();
104
105 auto *CastedPtr = CGF.EmitScalarConversion(
106 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
107 Ctx.getPointerType(DstType), SourceLocation());
108 auto TmpAddr =
109 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
110 .getAddress();
111
112 // If we are dealing with references we need to return the address of the
113 // reference instead of the reference of the value.
114 if (isReferenceType) {
115 QualType RefType = Ctx.getLValueReferenceType(DstType);
116 auto *RefVal = TmpAddr.getPointer();
117 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
118 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
119 CGF.EmitScalarInit(RefVal, TmpLVal);
120 }
121
122 return TmpAddr;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 assert(
128 CapturedStmtInfo &&
129 "CapturedStmtInfo should be set when generating the captured function");
130 const CapturedDecl *CD = S.getCapturedDecl();
131 const RecordDecl *RD = S.getCapturedRecordDecl();
132 assert(CD->hasBody() && "missing CapturedDecl body");
133
134 // Build the argument list.
135 ASTContext &Ctx = CGM.getContext();
136 FunctionArgList Args;
137 Args.append(CD->param_begin(),
138 std::next(CD->param_begin(), CD->getContextParamPosition()));
139 auto I = S.captures().begin();
140 for (auto *FD : RD->fields()) {
141 QualType ArgType = FD->getType();
142 IdentifierInfo *II = nullptr;
143 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000144
145 // If this is a capture by copy and the type is not a pointer, the outlined
146 // function argument type should be uintptr and the value properly casted to
147 // uintptr. This is necessary given that the runtime library is only able to
148 // deal with pointers. We can pass in the same way the VLA type sizes to the
149 // outlined function.
150 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
151 I->capturesVariableArrayType())
152 ArgType = Ctx.getUIntPtrType();
153
154 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000155 CapVar = I->getCapturedVar();
156 II = CapVar->getIdentifier();
157 } else if (I->capturesThis())
158 II = &getContext().Idents.get("this");
159 else {
160 assert(I->capturesVariableArrayType());
161 II = &getContext().Idents.get("vla");
162 }
163 if (ArgType->isVariablyModifiedType())
164 ArgType = getContext().getVariableArrayDecayedType(ArgType);
165 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
166 FD->getLocation(), II, ArgType));
167 ++I;
168 }
169 Args.append(
170 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
171 CD->param_end());
172
173 // Create the function declaration.
174 FunctionType::ExtInfo ExtInfo;
175 const CGFunctionInfo &FuncInfo =
176 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
177 /*IsVariadic=*/false);
178 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
179
180 llvm::Function *F = llvm::Function::Create(
181 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
182 CapturedStmtInfo->getHelperName(), &CGM.getModule());
183 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
184 if (CD->isNothrow())
185 F->addFnAttr(llvm::Attribute::NoUnwind);
186
187 // Generate the function.
188 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
189 CD->getBody()->getLocStart());
190 unsigned Cnt = CD->getContextParamPosition();
191 I = S.captures().begin();
192 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193 // If we are capturing a pointer by copy we don't need to do anything, just
194 // use the value that we get from the arguments.
195 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
196 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000197 ++Cnt;
198 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 continue;
200 }
201
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 LValue ArgLVal =
203 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
204 AlignmentSource::Decl);
205 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206 LValue CastedArgLVal =
207 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
208 Args[Cnt]->getName(), ArgLVal),
209 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000210 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000211 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000212 auto VAT = FD->getCapturedVLAType();
213 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
214 } else if (I->capturesVariable()) {
215 auto *Var = I->getCapturedVar();
216 QualType VarTy = Var->getType();
217 Address ArgAddr = ArgLVal.getAddress();
218 if (!VarTy->isReferenceType()) {
219 ArgAddr = EmitLoadOfReference(
220 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
221 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000222 setAddrOfLocalVar(
223 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 } else if (I->capturesVariableByCopy()) {
225 assert(!FD->getType()->isAnyPointerType() &&
226 "Not expecting a captured pointer.");
227 auto *Var = I->getCapturedVar();
228 QualType VarTy = Var->getType();
229 setAddrOfLocalVar(I->getCapturedVar(),
230 castValueFromUintptr(*this, FD->getType(),
231 Args[Cnt]->getName(), ArgLVal,
232 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 } else {
234 // If 'this' is captured, load it into CXXThisValue.
235 assert(I->capturesThis());
236 CXXThisValue =
237 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
238 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000239 ++Cnt;
240 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241 }
242
Serge Pavlov3a561452015-12-06 14:32:39 +0000243 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 CapturedStmtInfo->EmitBody(*this, CD->getBody());
245 FinishFunction(CD->getBodyRBrace());
246
247 return F;
248}
249
Alexey Bataev9959db52014-05-06 10:08:46 +0000250//===----------------------------------------------------------------------===//
251// OpenMP Directive Emission
252//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000253void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address DestAddr, Address SrcAddr, QualType OriginalType,
255 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000256 // Perform element-by-element initialization.
257 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000258
259 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000261 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
262 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
263
264 auto SrcBegin = SrcAddr.getPointer();
265 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
268 // The basic structure here is a while-do loop.
269 auto BodyBB = createBasicBlock("omp.arraycpy.body");
270 auto DoneBB = createBasicBlock("omp.arraycpy.done");
271 auto IsEmpty =
272 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
273 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000274
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Enter the loop body, making that address the current address.
276 auto EntryBB = Builder.GetInsertBlock();
277 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000278
279 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
280
281 llvm::PHINode *SrcElementPHI =
282 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
283 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
284 Address SrcElementCurrent =
285 Address(SrcElementPHI,
286 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
287
288 llvm::PHINode *DestElementPHI =
289 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
290 DestElementPHI->addIncoming(DestBegin, EntryBB);
291 Address DestElementCurrent =
292 Address(DestElementPHI,
293 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000294
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Emit copy.
296 CopyGen(DestElementCurrent, SrcElementCurrent);
297
298 // Shift the address forward by one element.
299 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000300 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000302 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000303 // Check whether we've reached the end.
304 auto Done =
305 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
306 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000307 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
308 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000309
310 // Done.
311 EmitBlock(DoneBB, /*IsFinished=*/true);
312}
313
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000314/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000315/// \param DestAddr Address of the array.
316/// \param Type Type of array.
317/// \param Init Initial expression of array.
318static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
319 QualType Type, const Expr *Init) {
320 // Perform element-by-element initialization.
321 QualType ElementTy;
322
323 // Drill down to the base element type on both arrays.
324 auto ArrayTy = Type->getAsArrayTypeUnsafe();
325 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
326 DestAddr =
327 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
328
329 auto DestBegin = DestAddr.getPointer();
330 // Cast from pointer to array type to pointer to single element.
331 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
332 // The basic structure here is a while-do loop.
333 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
334 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
335 auto IsEmpty =
336 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
337 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
338
339 // Enter the loop body, making that address the current address.
340 auto EntryBB = CGF.Builder.GetInsertBlock();
341 CGF.EmitBlock(BodyBB);
342
343 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
344
345 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
346 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
347 DestElementPHI->addIncoming(DestBegin, EntryBB);
348 Address DestElementCurrent =
349 Address(DestElementPHI,
350 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
351
352 // Emit copy.
353 {
354 CodeGenFunction::RunCleanupsScope InitScope(CGF);
355 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
356 /*IsInitializer=*/false);
357 }
358
359 // Shift the address forward by one element.
360 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
361 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
362 // Check whether we've reached the end.
363 auto Done =
364 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
365 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
366 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
367
368 // Done.
369 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
370}
371
John McCall7f416cc2015-09-08 08:05:57 +0000372void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
373 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000374 const VarDecl *SrcVD, const Expr *Copy) {
375 if (OriginalType->isArrayType()) {
376 auto *BO = dyn_cast<BinaryOperator>(Copy);
377 if (BO && BO->getOpcode() == BO_Assign) {
378 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000379 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000380 } else {
381 // For arrays with complex element types perform element by element
382 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000383 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000384 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000385 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386 // Working with the single array element, so have to remap
387 // destination and source variables to corresponding array
388 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000389 CodeGenFunction::OMPPrivateScope Remap(*this);
390 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 return DestElement;
392 });
393 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000394 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000395 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000396 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000397 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000398 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 } else {
400 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000401 CodeGenFunction::OMPPrivateScope Remap(*this);
402 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
403 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 (void)Remap.Privatize();
405 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000406 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000407 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000408}
409
Alexey Bataev69c62a92015-04-15 04:52:20 +0000410bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
411 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000412 if (!HaveInsertPoint())
413 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000414 bool FirstprivateIsLastprivate = false;
415 llvm::DenseSet<const VarDecl *> Lastprivates;
416 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
417 for (const auto *D : C->varlists())
418 Lastprivates.insert(
419 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
420 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000421 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000422 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423 auto IRef = C->varlist_begin();
424 auto InitsRef = C->inits().begin();
425 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000426 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000427 FirstprivateIsLastprivate =
428 FirstprivateIsLastprivate ||
429 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
430 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000431 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
432 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
433 bool IsRegistered;
434 DeclRefExpr DRE(
435 const_cast<VarDecl *>(OrigVD),
436 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
437 OrigVD) != nullptr,
438 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000439 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000440 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000441 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 // Emit VarDecl with copy init for arrays.
443 // Get the address of the original variable captured in current
444 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000445 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 auto Emission = EmitAutoVarAlloca(*VD);
447 auto *Init = VD->getInit();
448 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
449 // Perform simple memcpy.
450 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000451 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000452 } else {
453 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000454 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000455 [this, VDInit, Init](Address DestElement,
456 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 // Clean up any temporaries needed by the initialization.
458 RunCleanupsScope InitScope(*this);
459 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000460 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000461 EmitAnyExprToMem(Init, DestElement,
462 Init->getType().getQualifiers(),
463 /*IsInitializer*/ false);
464 LocalDeclMap.erase(VDInit);
465 });
466 }
467 EmitAutoVarCleanups(Emission);
468 return Emission.getAllocatedAddress();
469 });
470 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000471 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000472 // Emit private VarDecl with copy init.
473 // Remap temp VDInit variable to the address of the original
474 // variable
475 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000476 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 EmitDecl(*VD);
478 LocalDeclMap.erase(VDInit);
479 return GetAddrOfLocalVar(VD);
480 });
481 }
482 assert(IsRegistered &&
483 "firstprivate var already registered as private");
484 // Silence the warning about unused variable.
485 (void)IsRegistered;
486 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000487 ++IRef;
488 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000489 }
490 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000491 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492}
493
Alexey Bataev03b340a2014-10-21 03:16:40 +0000494void CodeGenFunction::EmitOMPPrivateClause(
495 const OMPExecutableDirective &D,
496 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000497 if (!HaveInsertPoint())
498 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000499 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000500 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000501 auto IRef = C->varlist_begin();
502 for (auto IInit : C->private_copies()) {
503 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000504 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
505 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
506 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000507 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 // Emit private VarDecl with copy init.
509 EmitDecl(*VD);
510 return GetAddrOfLocalVar(VD);
511 });
512 assert(IsRegistered && "private var already registered as private");
513 // Silence the warning about unused variable.
514 (void)IsRegistered;
515 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000516 ++IRef;
517 }
518 }
519}
520
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000521bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000522 if (!HaveInsertPoint())
523 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000524 // threadprivate_var1 = master_threadprivate_var1;
525 // operator=(threadprivate_var2, master_threadprivate_var2);
526 // ...
527 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 llvm::DenseSet<const VarDecl *> CopiedVars;
529 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000530 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000531 auto IRef = C->varlist_begin();
532 auto ISrcRef = C->source_exprs().begin();
533 auto IDestRef = C->destination_exprs().begin();
534 for (auto *AssignOp : C->assignment_ops()) {
535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000536 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000537 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000538 // Get the address of the master variable. If we are emitting code with
539 // TLS support, the address is passed from the master as field in the
540 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 if (getLangOpts().OpenMPUseTLS &&
543 getContext().getTargetInfo().isTLSSupported()) {
544 assert(CapturedStmtInfo->lookup(VD) &&
545 "Copyin threadprivates should have been captured!");
546 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
547 VK_LValue, (*IRef)->getExprLoc());
548 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000549 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000550 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000551 MasterAddr =
552 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
553 : CGM.GetAddrOfGlobal(VD),
554 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000555 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000556 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000557 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000558 if (CopiedVars.size() == 1) {
559 // At first check if current thread is a master thread. If it is, no
560 // need to copy data.
561 CopyBegin = createBasicBlock("copyin.not.master");
562 CopyEnd = createBasicBlock("copyin.not.master.end");
563 Builder.CreateCondBr(
564 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000565 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
566 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000567 CopyBegin, CopyEnd);
568 EmitBlock(CopyBegin);
569 }
570 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
571 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000572 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000573 }
574 ++IRef;
575 ++ISrcRef;
576 ++IDestRef;
577 }
578 }
579 if (CopyEnd) {
580 // Exit out of copying procedure for non-master thread.
581 EmitBlock(CopyEnd, /*IsFinished=*/true);
582 return true;
583 }
584 return false;
585}
586
Alexey Bataev38e89532015-04-16 04:54:05 +0000587bool CodeGenFunction::EmitOMPLastprivateClauseInit(
588 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000591 bool HasAtLeastOneLastprivate = false;
592 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000594 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 auto IRef = C->varlist_begin();
596 auto IDestRef = C->destination_exprs().begin();
597 for (auto *IInit : C->private_copies()) {
598 // Keep the address of the original variable for future update at the end
599 // of the loop.
600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
601 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
602 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000603 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000604 DeclRefExpr DRE(
605 const_cast<VarDecl *>(OrigVD),
606 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
607 OrigVD) != nullptr,
608 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
609 return EmitLValue(&DRE).getAddress();
610 });
611 // Check if the variable is also a firstprivate: in this case IInit is
612 // not generated. Initialization of this variable will happen in codegen
613 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000614 if (IInit) {
615 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
616 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000617 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 // Emit private VarDecl with copy init.
619 EmitDecl(*VD);
620 return GetAddrOfLocalVar(VD);
621 });
622 assert(IsRegistered &&
623 "lastprivate var already registered as private");
624 (void)IsRegistered;
625 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000626 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000627 ++IRef;
628 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000629 }
630 }
631 return HasAtLeastOneLastprivate;
632}
633
634void CodeGenFunction::EmitOMPLastprivateClauseFinal(
635 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000636 if (!HaveInsertPoint())
637 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000638 // Emit following code:
639 // if (<IsLastIterCond>) {
640 // orig_var1 = private_orig_var1;
641 // ...
642 // orig_varn = private_orig_varn;
643 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000644 llvm::BasicBlock *ThenBB = nullptr;
645 llvm::BasicBlock *DoneBB = nullptr;
646 if (IsLastIterCond) {
647 ThenBB = createBasicBlock(".omp.lastprivate.then");
648 DoneBB = createBasicBlock(".omp.lastprivate.done");
649 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
650 EmitBlock(ThenBB);
651 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000652 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000653 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000654 auto IC = LoopDirective->counters().begin();
655 for (auto F : LoopDirective->finals()) {
656 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
657 LoopCountersAndUpdates[D] = F;
658 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000659 }
660 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000661 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
662 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
663 auto IRef = C->varlist_begin();
664 auto ISrcRef = C->source_exprs().begin();
665 auto IDestRef = C->destination_exprs().begin();
666 for (auto *AssignOp : C->assignment_ops()) {
667 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
668 QualType Type = PrivateVD->getType();
669 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
670 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
671 // If lastprivate variable is a loop control variable for loop-based
672 // directive, update its value before copyin back to original
673 // variable.
674 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
675 EmitIgnoredExpr(UpExpr);
676 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
677 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
678 // Get the address of the original variable.
679 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
680 // Get the address of the private variable.
681 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
682 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
683 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000684 Address(Builder.CreateLoad(PrivateAddr),
685 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000686 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000688 ++IRef;
689 ++ISrcRef;
690 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000692 if (auto *PostUpdate = C->getPostUpdateExpr())
693 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000694 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000695 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000696 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000697}
698
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
700 LValue BaseLV, llvm::Value *Addr) {
701 Address Tmp = Address::invalid();
702 Address TopTmp = Address::invalid();
703 Address MostTopTmp = Address::invalid();
704 BaseTy = BaseTy.getNonReferenceType();
705 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
706 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
707 Tmp = CGF.CreateMemTemp(BaseTy);
708 if (TopTmp.isValid())
709 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
710 else
711 MostTopTmp = Tmp;
712 TopTmp = Tmp;
713 BaseTy = BaseTy->getPointeeType();
714 }
715 llvm::Type *Ty = BaseLV.getPointer()->getType();
716 if (Tmp.isValid())
717 Ty = Tmp.getElementType();
718 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
719 if (Tmp.isValid()) {
720 CGF.Builder.CreateStore(Addr, Tmp);
721 return MostTopTmp;
722 }
723 return Address(Addr, BaseLV.getAlignment());
724}
725
726static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
727 LValue BaseLV) {
728 BaseTy = BaseTy.getNonReferenceType();
729 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
730 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
731 if (auto *PtrTy = BaseTy->getAs<PointerType>())
732 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
733 else {
734 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
735 BaseTy->castAs<ReferenceType>());
736 }
737 BaseTy = BaseTy->getPointeeType();
738 }
739 return CGF.MakeAddrLValue(
740 Address(
741 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
742 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
743 BaseLV.getAlignment()),
744 BaseLV.getType(), BaseLV.getAlignmentSource());
745}
746
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000747void CodeGenFunction::EmitOMPReductionClauseInit(
748 const OMPExecutableDirective &D,
749 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000750 if (!HaveInsertPoint())
751 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000752 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000753 auto ILHS = C->lhs_exprs().begin();
754 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000755 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000756 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000757 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000758 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
760 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
761 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
762 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
763 Base = TempOASE->getBase()->IgnoreParenImpCasts();
764 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
765 Base = TempASE->getBase()->IgnoreParenImpCasts();
766 auto *DE = cast<DeclRefExpr>(Base);
767 auto *OrigVD = cast<VarDecl>(DE->getDecl());
768 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
769 auto OASELValueUB =
770 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
771 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000772 LValue BaseLValue =
773 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
774 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000775 // Store the address of the original variable associated with the LHS
776 // implicit variable.
777 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
778 return OASELValueLB.getAddress();
779 });
780 // Emit reduction copy.
781 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000782 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
783 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000784 // Emit VarDecl with copy init for arrays.
785 // Get the address of the original variable captured in current
786 // captured region.
787 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
788 OASELValueLB.getPointer());
789 Size = Builder.CreateNUWAdd(
790 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
791 CodeGenFunction::OpaqueValueMapping OpaqueMap(
792 *this, cast<OpaqueValueExpr>(
793 getContext()
794 .getAsVariableArrayType(PrivateVD->getType())
795 ->getSizeExpr()),
796 RValue::get(Size));
797 EmitVariablyModifiedType(PrivateVD->getType());
798 auto Emission = EmitAutoVarAlloca(*PrivateVD);
799 auto Addr = Emission.getAllocatedAddress();
800 auto *Init = PrivateVD->getInit();
801 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
802 EmitAutoVarCleanups(Emission);
803 // Emit private VarDecl with reduction init.
804 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
805 OASELValueLB.getPointer());
806 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000807 return castToBase(*this, OrigVD->getType(),
808 OASELValueLB.getType(), OriginalBaseLValue,
809 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000810 });
811 assert(IsRegistered && "private var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
815 return GetAddrOfLocalVar(PrivateVD);
816 });
817 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
818 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
819 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
820 Base = TempASE->getBase()->IgnoreParenImpCasts();
821 auto *DE = cast<DeclRefExpr>(Base);
822 auto *OrigVD = cast<VarDecl>(DE->getDecl());
823 auto ASELValue = EmitLValue(ASE);
824 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000825 LValue BaseLValue = loadToBegin(
826 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000827 // Store the address of the original variable associated with the LHS
828 // implicit variable.
829 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
830 return ASELValue.getAddress();
831 });
832 // Emit reduction copy.
833 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000834 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000835 OriginalBaseLValue]() -> Address {
836 // Emit private VarDecl with reduction init.
837 EmitDecl(*PrivateVD);
838 auto Addr = GetAddrOfLocalVar(PrivateVD);
839 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
840 ASELValue.getPointer());
841 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000842 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
843 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000848 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
849 return Builder.CreateElementBitCast(
850 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
851 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000852 });
853 } else {
854 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000855 QualType Type = PrivateVD->getType();
856 if (getContext().getAsArrayType(Type)) {
857 // Store the address of the original variable associated with the LHS
858 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
860 CapturedStmtInfo->lookup(OrigVD) != nullptr,
861 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000862 Address OriginalAddr = EmitLValue(&DRE).getAddress();
863 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
864 LHSVD]() -> Address {
865 return Builder.CreateElementBitCast(
866 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
867 "lhs.begin");
868 });
869 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
870 if (Type->isVariablyModifiedType()) {
871 CodeGenFunction::OpaqueValueMapping OpaqueMap(
872 *this, cast<OpaqueValueExpr>(
873 getContext()
874 .getAsVariableArrayType(PrivateVD->getType())
875 ->getSizeExpr()),
876 RValue::get(
877 getTypeSize(OrigVD->getType().getNonReferenceType())));
878 EmitVariablyModifiedType(Type);
879 }
880 auto Emission = EmitAutoVarAlloca(*PrivateVD);
881 auto Addr = Emission.getAllocatedAddress();
882 auto *Init = PrivateVD->getInit();
883 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
884 EmitAutoVarCleanups(Emission);
885 return Emission.getAllocatedAddress();
886 });
887 assert(IsRegistered && "private var already registered as private");
888 // Silence the warning about unused variable.
889 (void)IsRegistered;
890 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
891 return Builder.CreateElementBitCast(
892 GetAddrOfLocalVar(PrivateVD),
893 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
894 });
895 } else {
896 // Store the address of the original variable associated with the LHS
897 // implicit variable.
898 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
899 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
900 CapturedStmtInfo->lookup(OrigVD) != nullptr,
901 IRef->getType(), VK_LValue, IRef->getExprLoc());
902 return EmitLValue(&DRE).getAddress();
903 });
904 // Emit reduction copy.
905 bool IsRegistered =
906 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
907 // Emit private VarDecl with reduction init.
908 EmitDecl(*PrivateVD);
909 return GetAddrOfLocalVar(PrivateVD);
910 });
911 assert(IsRegistered && "private var already registered as private");
912 // Silence the warning about unused variable.
913 (void)IsRegistered;
914 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
915 return GetAddrOfLocalVar(PrivateVD);
916 });
917 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000918 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000919 ++ILHS;
920 ++IRHS;
921 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000922 }
923 }
924}
925
926void CodeGenFunction::EmitOMPReductionClauseFinal(
927 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000928 if (!HaveInsertPoint())
929 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000931 llvm::SmallVector<const Expr *, 8> LHSExprs;
932 llvm::SmallVector<const Expr *, 8> RHSExprs;
933 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000934 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000936 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000937 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000938 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
939 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
940 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
941 }
942 if (HasAtLeastOneReduction) {
943 // Emit nowait reduction if nowait clause is present or directive is a
944 // parallel directive (it always has implicit barrier).
945 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000946 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000947 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000948 isOpenMPParallelDirective(D.getDirectiveKind()) ||
949 D.getDirectiveKind() == OMPD_simd,
950 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000951 }
952}
953
Alexey Bataev61205072016-03-02 04:57:40 +0000954static void emitPostUpdateForReductionClause(
955 CodeGenFunction &CGF, const OMPExecutableDirective &D,
956 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
957 if (!CGF.HaveInsertPoint())
958 return;
959 llvm::BasicBlock *DoneBB = nullptr;
960 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
961 if (auto *PostUpdate = C->getPostUpdateExpr()) {
962 if (!DoneBB) {
963 if (auto *Cond = CondGen(CGF)) {
964 // If the first post-update expression is found, emit conditional
965 // block if it was requested.
966 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
967 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
968 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
969 CGF.EmitBlock(ThenBB);
970 }
971 }
972 CGF.EmitIgnoredExpr(PostUpdate);
973 }
974 }
975 if (DoneBB)
976 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
977}
978
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
980 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000981 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000982 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000983 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000984 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
985 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000986 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
987 emitParallelOrTeamsOutlinedFunction(S,
988 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000989 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000990 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000991 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
992 /*IgnoreResultAssign*/ true);
993 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
994 CGF, NumThreads, NumThreadsClause->getLocStart());
995 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000996 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000997 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000998 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
999 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1000 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001001 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001002 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1003 if (C->getNameModifier() == OMPD_unknown ||
1004 C->getNameModifier() == OMPD_parallel) {
1005 IfCond = C->getCondition();
1006 break;
1007 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001008 }
1009 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001010 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001011}
1012
1013void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001014 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001015 // Emit parallel region as a standalone region.
1016 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1017 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001018 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001019 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1020 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001021 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001022 // propagation master's thread values of threadprivate variables to local
1023 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001024 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1025 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1026 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001027 }
1028 CGF.EmitOMPPrivateClause(S, PrivateScope);
1029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1030 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001031 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001032 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001033 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001034 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001035 emitPostUpdateForReductionClause(
1036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001037}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001038
Alexey Bataev0f34da12015-07-02 04:17:07 +00001039void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1040 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001041 RunCleanupsScope BodyScope(*this);
1042 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001043 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001044 EmitIgnoredExpr(I);
1045 }
Alexander Musman3276a272015-03-21 10:12:56 +00001046 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001047 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001048 for (auto U : C->updates()) {
1049 EmitIgnoredExpr(U);
1050 }
1051 }
1052
Alexander Musmana5f070a2014-10-01 06:03:56 +00001053 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001054 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001055 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001057 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001058 // The end (updates/cleanups).
1059 EmitBlock(Continue.getBlock());
1060 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001061}
1062
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001063void CodeGenFunction::EmitOMPInnerLoop(
1064 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1065 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001066 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1067 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001068 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001069
1070 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001071 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001072 EmitBlock(CondBlock);
1073 LoopStack.push(CondBlock);
1074
1075 // If there are any cleanups between here and the loop-exit scope,
1076 // create a block to stage a loop exit along.
1077 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001078 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001079 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001080
Alexander Musmand196ef22014-10-07 08:57:09 +00001081 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001082
Alexey Bataev2df54a02015-03-12 08:53:29 +00001083 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001084 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001085 if (ExitBlock != LoopExit.getBlock()) {
1086 EmitBlock(ExitBlock);
1087 EmitBranchThroughCleanup(LoopExit);
1088 }
1089
1090 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001091 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001092
1093 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001094 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001095 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001097 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001098
1099 // Emit "IV = IV + 1" and a back-edge to the condition block.
1100 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001101 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001102 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001103 BreakContinueStack.pop_back();
1104 EmitBranch(CondBlock);
1105 LoopStack.pop();
1106 // Emit the fall-through block.
1107 EmitBlock(LoopExit.getBlock());
1108}
1109
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001110void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001111 if (!HaveInsertPoint())
1112 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001113 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001114 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001115 for (auto Init : C->inits()) {
1116 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001117 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1118 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1119 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1120 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1121 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1122 VD->getInit()->getType(), VK_LValue,
1123 VD->getInit()->getExprLoc());
1124 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1125 VD->getType()),
1126 /*capturedByInit=*/false);
1127 EmitAutoVarCleanups(Emission);
1128 } else
1129 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001130 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001131 // Emit the linear steps for the linear clauses.
1132 // If a step is not constant, it is pre-calculated before the loop.
1133 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1134 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001135 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001136 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001137 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001138 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001139 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001140}
1141
Alexey Bataevef549a82016-03-09 09:49:09 +00001142static void emitLinearClauseFinal(
1143 CodeGenFunction &CGF, const OMPLoopDirective &D,
1144 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001145 if (!CGF.HaveInsertPoint())
1146 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001147 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001148 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001149 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001150 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001151 for (auto F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001152 if (!DoneBB) {
1153 if (auto *Cond = CondGen(CGF)) {
1154 // If the first post-update expression is found, emit conditional
1155 // block if it was requested.
1156 auto *ThenBB = CGF.createBasicBlock(".omp.linear.pu");
1157 DoneBB = CGF.createBasicBlock(".omp.linear.pu.done");
1158 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1159 CGF.EmitBlock(ThenBB);
1160 }
1161 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001162 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1163 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001164 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001165 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001166 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001167 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001168 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001169 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001170 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001171 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001172 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001173 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001174 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataevef549a82016-03-09 09:49:09 +00001175 CGF.EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001176 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001177 if (DoneBB)
1178 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001179}
1180
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001181static void emitAlignedClause(CodeGenFunction &CGF,
1182 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001183 if (!CGF.HaveInsertPoint())
1184 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001185 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001186 unsigned ClauseAlignment = 0;
1187 if (auto AlignmentExpr = Clause->getAlignment()) {
1188 auto AlignmentCI =
1189 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1190 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001191 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001192 for (auto E : Clause->varlists()) {
1193 unsigned Alignment = ClauseAlignment;
1194 if (Alignment == 0) {
1195 // OpenMP [2.8.1, Description]
1196 // If no optional parameter is specified, implementation-defined default
1197 // alignments for SIMD instructions on the target platforms are assumed.
1198 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001199 CGF.getContext()
1200 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1201 E->getType()->getPointeeType()))
1202 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001203 }
1204 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1205 "alignment is not power of 2");
1206 if (Alignment != 0) {
1207 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1208 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1209 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001210 }
1211 }
1212}
1213
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001214static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001215 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001216 ArrayRef<Expr *> Counters,
1217 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001218 if (!CGF.HaveInsertPoint())
1219 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001220 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001221 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001222 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1223 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001224 Address Addr = Address::invalid();
1225 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001226 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001227 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001228 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001229 Addr = VarEmission.getAllocatedAddress();
1230 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001231 });
John McCall7f416cc2015-09-08 08:05:57 +00001232 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001233 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001234 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001235}
1236
Alexey Bataev62dbb972015-04-22 11:59:37 +00001237static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1238 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1239 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001240 if (!CGF.HaveInsertPoint())
1241 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001242 {
1243 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001244 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1245 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001246 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001247 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001248 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001249 CGF.EmitIgnoredExpr(I);
1250 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001251 }
1252 // Check that loop is executed at least one time.
1253 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1254}
1255
Alexander Musman3276a272015-03-21 10:12:56 +00001256static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001257emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001258 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001259 if (!CGF.HaveInsertPoint())
1260 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001261 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001262 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001263 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001264 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1265 auto *PrivateVD =
1266 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001267 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001268 // Emit private VarDecl with copy init.
1269 CGF.EmitVarDecl(*PrivateVD);
1270 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001271 });
1272 assert(IsRegistered && "linear var already registered as private");
1273 // Silence the warning about unused variable.
1274 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001275 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001276 }
1277 }
1278}
1279
Alexey Bataev45bfad52015-08-21 12:19:04 +00001280static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001281 const OMPExecutableDirective &D,
1282 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001283 if (!CGF.HaveInsertPoint())
1284 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001285 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001286 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1287 /*ignoreResult=*/true);
1288 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1289 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1290 // In presence of finite 'safelen', it may be unsafe to mark all
1291 // the memory instructions parallel, because loop-carried
1292 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001293 if (!IsMonotonic)
1294 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001295 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001296 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1297 /*ignoreResult=*/true);
1298 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001299 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001300 // In presence of finite 'safelen', it may be unsafe to mark all
1301 // the memory instructions parallel, because loop-carried
1302 // dependences of 'safelen' iterations are possible.
1303 CGF.LoopStack.setParallel(false);
1304 }
1305}
1306
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001307void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1308 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001310 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001311 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001312 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001313}
1314
Alexey Bataevef549a82016-03-09 09:49:09 +00001315void CodeGenFunction::EmitOMPSimdFinal(
1316 const OMPLoopDirective &D,
1317 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001318 if (!HaveInsertPoint())
1319 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001320 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001321 auto IC = D.counters().begin();
1322 for (auto F : D.finals()) {
1323 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001324 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001325 if (!DoneBB) {
1326 if (auto *Cond = CondGen(*this)) {
1327 // If the first post-update expression is found, emit conditional
1328 // block if it was requested.
1329 auto *ThenBB = createBasicBlock(".omp.final.then");
1330 DoneBB = createBasicBlock(".omp.final.done");
1331 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1332 EmitBlock(ThenBB);
1333 }
1334 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001335 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1336 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1337 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001338 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001339 OMPPrivateScope VarScope(*this);
1340 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001341 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001342 (void)VarScope.Privatize();
1343 EmitIgnoredExpr(F);
1344 }
1345 ++IC;
1346 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001347 if (DoneBB)
1348 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001349}
1350
Alexander Musman515ad8c2014-05-22 08:54:05 +00001351void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001353 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001354 // for (IV in 0..LastIteration) BODY;
1355 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001356 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001357 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358
Alexey Bataev62dbb972015-04-22 11:59:37 +00001359 // Emit: if (PreCond) - begin.
1360 // If the condition constant folds and can be elided, avoid emitting the
1361 // whole loop.
1362 bool CondConstant;
1363 llvm::BasicBlock *ContBlock = nullptr;
1364 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1365 if (!CondConstant)
1366 return;
1367 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001368 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1369 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001370 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1371 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001372 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001373 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001374 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001375
1376 // Emit the loop iteration variable.
1377 const Expr *IVExpr = S.getIterationVariable();
1378 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1379 CGF.EmitVarDecl(*IVDecl);
1380 CGF.EmitIgnoredExpr(S.getInit());
1381
1382 // Emit the iterations count variable.
1383 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001384 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001385 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1386 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1387 // Emit calculation of the iterations count.
1388 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001389 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001390
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001391 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001393 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001394 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001395 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001396 {
1397 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001398 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1399 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001400 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001401 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001402 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001403 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001404 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001405 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1406 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001407 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001408 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001409 CGF.EmitStopPoint(&S);
1410 },
1411 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001412 // Emit final copy of the lastprivate variables at the end of loops.
1413 if (HasLastprivateClause) {
1414 CGF.EmitOMPLastprivateClauseFinal(S);
1415 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001416 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001417 emitPostUpdateForReductionClause(
1418 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001419 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001420 CGF.EmitOMPSimdFinal(
1421 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1422 emitLinearClauseFinal(
1423 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001424 // Emit: if (PreCond) - end.
1425 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001426 CGF.EmitBranch(ContBlock);
1427 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001428 }
1429 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001430 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001431}
1432
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001433void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001434 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1435 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001436 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001437
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001438 const Expr *IVExpr = S.getIterationVariable();
1439 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1440 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1441
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001442 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1443
1444 // Start the loop with a block that tests the condition.
1445 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1446 EmitBlock(CondBlock);
1447 LoopStack.push(CondBlock);
1448
1449 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001450 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001451 // UB = min(UB, GlobalUB)
1452 EmitIgnoredExpr(S.getEnsureUpperBound());
1453 // IV = LB
1454 EmitIgnoredExpr(S.getInit());
1455 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001456 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001457 } else {
1458 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1459 IL, LB, UB, ST);
1460 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001461
1462 // If there are any cleanups between here and the loop-exit scope,
1463 // create a block to stage a loop exit along.
1464 auto ExitBlock = LoopExit.getBlock();
1465 if (LoopScope.requiresCleanups())
1466 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1467
1468 auto LoopBody = createBasicBlock("omp.dispatch.body");
1469 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1470 if (ExitBlock != LoopExit.getBlock()) {
1471 EmitBlock(ExitBlock);
1472 EmitBranchThroughCleanup(LoopExit);
1473 }
1474 EmitBlock(LoopBody);
1475
Alexander Musman92bdaab2015-03-12 13:37:50 +00001476 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1477 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001478 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001479 EmitIgnoredExpr(S.getInit());
1480
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001481 // Create a block for the increment.
1482 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1483 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1484
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001485 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1486 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001487 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1488 LoopStack.setParallel(!IsMonotonic);
1489 else
1490 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001491
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001492 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001493 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1494 [&S, LoopExit](CodeGenFunction &CGF) {
1495 CGF.EmitOMPLoopBody(S, LoopExit);
1496 CGF.EmitStopPoint(&S);
1497 },
1498 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1499 if (Ordered) {
1500 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1501 CGF, Loc, IVSize, IVSigned);
1502 }
1503 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001504
1505 EmitBlock(Continue.getBlock());
1506 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001507 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001508 // Emit "LB = LB + Stride", "UB = UB + Stride".
1509 EmitIgnoredExpr(S.getNextLowerBound());
1510 EmitIgnoredExpr(S.getNextUpperBound());
1511 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001512
1513 EmitBranch(CondBlock);
1514 LoopStack.pop();
1515 // Emit the fall-through block.
1516 EmitBlock(LoopExit.getBlock());
1517
1518 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001519 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001520 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001521
1522}
1523
1524void CodeGenFunction::EmitOMPForOuterLoop(
1525 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1526 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1527 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1528 auto &RT = CGM.getOpenMPRuntime();
1529
1530 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1531 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1532
1533 assert((Ordered ||
1534 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1535 "static non-chunked schedule does not need outer loop");
1536
1537 // Emit outer loop.
1538 //
1539 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1540 // When schedule(dynamic,chunk_size) is specified, the iterations are
1541 // distributed to threads in the team in chunks as the threads request them.
1542 // Each thread executes a chunk of iterations, then requests another chunk,
1543 // until no chunks remain to be distributed. Each chunk contains chunk_size
1544 // iterations, except for the last chunk to be distributed, which may have
1545 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1546 //
1547 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1548 // to threads in the team in chunks as the executing threads request them.
1549 // Each thread executes a chunk of iterations, then requests another chunk,
1550 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1551 // each chunk is proportional to the number of unassigned iterations divided
1552 // by the number of threads in the team, decreasing to 1. For a chunk_size
1553 // with value k (greater than 1), the size of each chunk is determined in the
1554 // same way, with the restriction that the chunks do not contain fewer than k
1555 // iterations (except for the last chunk to be assigned, which may have fewer
1556 // than k iterations).
1557 //
1558 // When schedule(auto) is specified, the decision regarding scheduling is
1559 // delegated to the compiler and/or runtime system. The programmer gives the
1560 // implementation the freedom to choose any possible mapping of iterations to
1561 // threads in the team.
1562 //
1563 // When schedule(runtime) is specified, the decision regarding scheduling is
1564 // deferred until run time, and the schedule and chunk size are taken from the
1565 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1566 // implementation defined
1567 //
1568 // while(__kmpc_dispatch_next(&LB, &UB)) {
1569 // idx = LB;
1570 // while (idx <= UB) { BODY; ++idx;
1571 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1572 // } // inner loop
1573 // }
1574 //
1575 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1576 // When schedule(static, chunk_size) is specified, iterations are divided into
1577 // chunks of size chunk_size, and the chunks are assigned to the threads in
1578 // the team in a round-robin fashion in the order of the thread number.
1579 //
1580 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1581 // while (idx <= UB) { BODY; ++idx; } // inner loop
1582 // LB = LB + ST;
1583 // UB = UB + ST;
1584 // }
1585 //
1586
1587 const Expr *IVExpr = S.getIterationVariable();
1588 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1589 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1590
1591 if (DynamicOrOrdered) {
1592 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1593 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1594 IVSize, IVSigned, Ordered, UBVal, Chunk);
1595 } else {
1596 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1597 Ordered, IL, LB, UB, ST, Chunk);
1598 }
1599
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001600 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001601 ST, IL, Chunk);
1602}
1603
1604void CodeGenFunction::EmitOMPDistributeOuterLoop(
1605 OpenMPDistScheduleClauseKind ScheduleKind,
1606 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1607 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1608
1609 auto &RT = CGM.getOpenMPRuntime();
1610
1611 // Emit outer loop.
1612 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1613 // dynamic
1614 //
1615
1616 const Expr *IVExpr = S.getIterationVariable();
1617 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1618 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1619
1620 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1621 IVSize, IVSigned, /* Ordered = */ false,
1622 IL, LB, UB, ST, Chunk);
1623
1624 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1625 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001626}
1627
Alexander Musmanc6388682014-12-15 07:07:06 +00001628/// \brief Emit a helper variable and return corresponding lvalue.
1629static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1630 const DeclRefExpr *Helper) {
1631 auto VDecl = cast<VarDecl>(Helper->getDecl());
1632 CGF.EmitVarDecl(*VDecl);
1633 return CGF.EmitLValue(Helper);
1634}
1635
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001636namespace {
1637 struct ScheduleKindModifiersTy {
1638 OpenMPScheduleClauseKind Kind;
1639 OpenMPScheduleClauseModifier M1;
1640 OpenMPScheduleClauseModifier M2;
1641 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1642 OpenMPScheduleClauseModifier M1,
1643 OpenMPScheduleClauseModifier M2)
1644 : Kind(Kind), M1(M1), M2(M2) {}
1645 };
1646} // namespace
1647
Alexey Bataev38e89532015-04-16 04:54:05 +00001648bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001649 // Emit the loop iteration variable.
1650 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1651 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1652 EmitVarDecl(*IVDecl);
1653
1654 // Emit the iterations count variable.
1655 // If it is not a variable, Sema decided to calculate iterations count on each
1656 // iteration (e.g., it is foldable into a constant).
1657 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1658 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1659 // Emit calculation of the iterations count.
1660 EmitIgnoredExpr(S.getCalcLastIteration());
1661 }
1662
1663 auto &RT = CGM.getOpenMPRuntime();
1664
Alexey Bataev38e89532015-04-16 04:54:05 +00001665 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001666 // Check pre-condition.
1667 {
1668 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001669 // If the condition constant folds and can be elided, avoid emitting the
1670 // whole loop.
1671 bool CondConstant;
1672 llvm::BasicBlock *ContBlock = nullptr;
1673 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1674 if (!CondConstant)
1675 return false;
1676 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001677 auto *ThenBlock = createBasicBlock("omp.precond.then");
1678 ContBlock = createBasicBlock("omp.precond.end");
1679 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001680 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001681 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001682 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001683 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001684
1685 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001686 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001687 // Emit helper vars inits.
1688 LValue LB =
1689 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1690 LValue UB =
1691 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1692 LValue ST =
1693 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1694 LValue IL =
1695 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1696
Alexander Musmanc6388682014-12-15 07:07:06 +00001697 // Emit 'then' code.
1698 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001699 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001700 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1701 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001702 // initialization of firstprivate variables and post-update of
1703 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001704 CGM.getOpenMPRuntime().emitBarrierCall(
1705 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1706 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001707 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001708 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001709 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001710 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001711 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1712 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001713 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001714 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001715
1716 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001717 llvm::Value *Chunk = nullptr;
1718 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1719 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1720 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1721 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1722 ScheduleKind = C->getScheduleKind();
1723 M1 = C->getFirstScheduleModifier();
1724 M2 = C->getSecondScheduleModifier();
1725 if (const auto *Ch = C->getChunkSize()) {
1726 Chunk = EmitScalarExpr(Ch);
1727 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1728 S.getIterationVariable()->getType(),
1729 S.getLocStart());
1730 }
1731 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001732 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1733 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001734 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001735 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1736 // If the static schedule kind is specified or if the ordered clause is
1737 // specified, and if no monotonic modifier is specified, the effect will
1738 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001739 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001740 /* Chunked */ Chunk != nullptr) &&
1741 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001742 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1743 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001744 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1745 // When no chunk_size is specified, the iteration space is divided into
1746 // chunks that are approximately equal in size, and at most one chunk is
1747 // distributed to each thread. Note that the size of the chunks is
1748 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001749 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1750 IVSize, IVSigned, Ordered,
1751 IL.getAddress(), LB.getAddress(),
1752 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001753 auto LoopExit =
1754 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001755 // UB = min(UB, GlobalUB);
1756 EmitIgnoredExpr(S.getEnsureUpperBound());
1757 // IV = LB;
1758 EmitIgnoredExpr(S.getInit());
1759 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001760 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1761 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001762 [&S, LoopExit](CodeGenFunction &CGF) {
1763 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001764 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001765 },
1766 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001767 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001768 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001769 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001770 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001771 const bool IsMonotonic = Ordered ||
1772 ScheduleKind == OMPC_SCHEDULE_static ||
1773 ScheduleKind == OMPC_SCHEDULE_unknown ||
1774 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1775 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001776 // Emit the outer loop, which requests its work chunk [LB..UB] from
1777 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001778 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001779 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1780 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001781 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001782 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001783 // Emit post-update of the reduction variables if IsLastIter != 0.
1784 emitPostUpdateForReductionClause(
1785 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1786 return CGF.Builder.CreateIsNotNull(
1787 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1788 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001789 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1790 if (HasLastprivateClause)
1791 EmitOMPLastprivateClauseFinal(
1792 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001793 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001794 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001795 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1796 return CGF.Builder.CreateIsNotNull(
1797 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1798 });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001799 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001800 emitLinearClauseFinal(*this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1801 return CGF.Builder.CreateIsNotNull(
1802 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1803 });
Alexander Musmanc6388682014-12-15 07:07:06 +00001804 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001805 if (ContBlock) {
1806 EmitBranch(ContBlock);
1807 EmitBlock(ContBlock, true);
1808 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001809 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001810 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001811}
1812
1813void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001814 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001815 {
1816 OMPLexicalScope Scope(*this, S);
1817 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1818 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1819 };
1820 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1821 S.hasCancel());
1822 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001823
1824 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001825 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001826 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1827 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001828}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001829
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001830void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001831 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001832 {
1833 OMPLexicalScope Scope(*this, S);
1834 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1835 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1836 };
1837 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1838 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001839
1840 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001841 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001842 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1843 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001844}
1845
Alexey Bataev2df54a02015-03-12 08:53:29 +00001846static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1847 const Twine &Name,
1848 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001849 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001850 if (Init)
1851 CGF.EmitScalarInit(Init, LVal);
1852 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001853}
1854
Alexey Bataev3392d762016-02-16 11:18:12 +00001855void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001856 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1857 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001858 bool HasLastprivates = false;
1859 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1860 auto &C = CGF.CGM.getContext();
1861 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1862 // Emit helper vars inits.
1863 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1864 CGF.Builder.getInt32(0));
1865 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1866 : CGF.Builder.getInt32(0);
1867 LValue UB =
1868 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1869 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1870 CGF.Builder.getInt32(1));
1871 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1872 CGF.Builder.getInt32(0));
1873 // Loop counter.
1874 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1875 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1876 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1877 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1878 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1879 // Generate condition for loop.
1880 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1881 OK_Ordinary, S.getLocStart(),
1882 /*fpContractable=*/false);
1883 // Increment for loop counter.
1884 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1885 S.getLocStart());
1886 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1887 // Iterate through all sections and emit a switch construct:
1888 // switch (IV) {
1889 // case 0:
1890 // <SectionStmt[0]>;
1891 // break;
1892 // ...
1893 // case <NumSection> - 1:
1894 // <SectionStmt[<NumSection> - 1]>;
1895 // break;
1896 // }
1897 // .omp.sections.exit:
1898 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1899 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1900 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1901 CS == nullptr ? 1 : CS->size());
1902 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001903 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001904 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001905 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1906 CGF.EmitBlock(CaseBB);
1907 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001908 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001909 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001910 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001911 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001912 } else {
1913 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1914 CGF.EmitBlock(CaseBB);
1915 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1916 CGF.EmitStmt(Stmt);
1917 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001918 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001919 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001920 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001921
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001922 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1923 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001924 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001925 // initialization of firstprivate variables and post-update of lastprivate
1926 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001927 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1928 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1929 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001930 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001931 CGF.EmitOMPPrivateClause(S, LoopScope);
1932 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1933 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1934 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001935
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001936 // Emit static non-chunked loop.
1937 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1938 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1939 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1940 UB.getAddress(), ST.getAddress());
1941 // UB = min(UB, GlobalUB);
1942 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1943 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1944 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1945 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1946 // IV = LB;
1947 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1948 // while (idx <= UB) { BODY; ++idx; }
1949 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1950 [](CodeGenFunction &) {});
1951 // Tell the runtime we are done.
1952 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1953 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001954 // Emit post-update of the reduction variables if IsLastIter != 0.
1955 emitPostUpdateForReductionClause(
1956 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1957 return CGF.Builder.CreateIsNotNull(
1958 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1959 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001960
1961 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1962 if (HasLastprivates)
1963 CGF.EmitOMPLastprivateClauseFinal(
1964 S, CGF.Builder.CreateIsNotNull(
1965 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001966 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001967
1968 bool HasCancel = false;
1969 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1970 HasCancel = OSD->hasCancel();
1971 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1972 HasCancel = OPSD->hasCancel();
1973 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1974 HasCancel);
1975 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1976 // clause. Otherwise the barrier will be generated by the codegen for the
1977 // directive.
1978 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001979 // Emit implicit barrier to synchronize threads and avoid data races on
1980 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001981 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1982 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001983 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001984}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001985
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001986void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001987 {
1988 OMPLexicalScope Scope(*this, S);
1989 EmitSections(S);
1990 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001991 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001992 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001993 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1994 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001995 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001996}
1997
1998void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001999 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002000 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2001 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002002 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00002003 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2004 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002005}
2006
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002007void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002008 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002009 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002010 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002011 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002012 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002013 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002014 // Build a list of copyprivate variables along with helper expressions
2015 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002016 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002017 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002018 DestExprs.append(C->destination_exprs().begin(),
2019 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002020 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002021 AssignmentOps.append(C->assignment_ops().begin(),
2022 C->assignment_ops().end());
2023 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002024 {
2025 OMPLexicalScope Scope(*this, S);
2026 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00002027 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002028 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00002029 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00002030 CGF.EmitOMPPrivateClause(S, SingleScope);
2031 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00002032 CGF.EmitStmt(
2033 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2034 };
2035 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2036 CopyprivateVars, DestExprs,
2037 SrcExprs, AssignmentOps);
2038 }
2039 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2040 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002041 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002042 CGM.getOpenMPRuntime().emitBarrierCall(
2043 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002044 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002045 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002046}
2047
Alexey Bataev8d690652014-12-04 07:23:53 +00002048void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002049 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002050 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2051 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002052 };
2053 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002054}
2055
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002056void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002057 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002058 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2059 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002060 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002061 Expr *Hint = nullptr;
2062 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2063 Hint = HintClause->getHint();
2064 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2065 S.getDirectiveName().getAsString(),
2066 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002067}
2068
Alexey Bataev671605e2015-04-13 05:28:11 +00002069void CodeGenFunction::EmitOMPParallelForDirective(
2070 const OMPParallelForDirective &S) {
2071 // Emit directive as a combined directive that consists of two implicit
2072 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002073 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002074 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2075 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002076 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002077 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002078}
2079
Alexander Musmane4e893b2014-09-23 09:33:00 +00002080void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002081 const OMPParallelForSimdDirective &S) {
2082 // Emit directive as a combined directive that consists of two implicit
2083 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002084 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002085 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2086 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002087 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002088 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002089}
2090
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002091void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002092 const OMPParallelSectionsDirective &S) {
2093 // Emit directive as a combined directive that consists of two implicit
2094 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002095 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002096 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002097 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002098}
2099
Alexey Bataev62b63b12015-03-10 07:28:44 +00002100void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2101 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002102 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002103 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2104 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2105 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002106 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002107 // The first function argument for tasks is a thread id, the second one is a
2108 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002109 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2110 // Get list of private variables.
2111 llvm::SmallVector<const Expr *, 8> PrivateVars;
2112 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002113 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002114 auto IRef = C->varlist_begin();
2115 for (auto *IInit : C->private_copies()) {
2116 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2117 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2118 PrivateVars.push_back(*IRef);
2119 PrivateCopies.push_back(IInit);
2120 }
2121 ++IRef;
2122 }
2123 }
2124 EmittedAsPrivate.clear();
2125 // Get list of firstprivate variables.
2126 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2127 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2128 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002129 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002130 auto IRef = C->varlist_begin();
2131 auto IElemInitRef = C->inits().begin();
2132 for (auto *IInit : C->private_copies()) {
2133 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2134 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2135 FirstprivateVars.push_back(*IRef);
2136 FirstprivateCopies.push_back(IInit);
2137 FirstprivateInits.push_back(*IElemInitRef);
2138 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002139 ++IRef;
2140 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002141 }
2142 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002143 // Build list of dependences.
2144 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2145 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002146 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002147 for (auto *IRef : C->varlists()) {
2148 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2149 }
2150 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002151 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2152 CodeGenFunction &CGF) {
2153 // Set proper addresses for generated private copies.
2154 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2155 OMPPrivateScope Scope(CGF);
2156 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002157 auto *CopyFn = CGF.Builder.CreateLoad(
2158 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2159 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2160 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002161 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002162 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002163 PrivatePtrs;
2164 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2165 CallArgs.push_back(PrivatesPtr);
2166 for (auto *E : PrivateVars) {
2167 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002168 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002169 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2170 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002171 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002172 }
2173 for (auto *E : FirstprivateVars) {
2174 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002175 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002176 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2177 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002178 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002179 }
2180 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2181 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002182 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2183 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002184 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2185 }
2186 }
2187 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002188 if (*PartId) {
2189 // TODO: emit code for untied tasks.
2190 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002191 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002192 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002193 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2194 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002195 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002196 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002197 // Check if the task is final
2198 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002199 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002200 // If the condition constant folds and can be elided, try to avoid emitting
2201 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002202 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002203 bool CondConstant;
2204 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2205 Final.setInt(CondConstant);
2206 else
2207 Final.setPointer(EvaluateExprAsBool(Cond));
2208 } else {
2209 // By default the task is not final.
2210 Final.setInt(/*IntVal=*/false);
2211 }
2212 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002213 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002214 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2215 if (C->getNameModifier() == OMPD_unknown ||
2216 C->getNameModifier() == OMPD_task) {
2217 IfCond = C->getCondition();
2218 break;
2219 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002220 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002221 CGM.getOpenMPRuntime().emitTaskCall(
2222 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002223 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002224 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002225}
2226
Alexey Bataev9f797f32015-02-05 05:57:51 +00002227void CodeGenFunction::EmitOMPTaskyieldDirective(
2228 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002229 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002230}
2231
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002232void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002233 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002234}
2235
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002236void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2237 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002238}
2239
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002240void CodeGenFunction::EmitOMPTaskgroupDirective(
2241 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002242 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002243 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2244 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002245 };
2246 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2247}
2248
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002249void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002250 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002251 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002252 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2253 FlushClause->varlist_end());
2254 }
2255 return llvm::None;
2256 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002257}
2258
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002259void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2260 // Emit the loop iteration variable.
2261 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2262 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2263 EmitVarDecl(*IVDecl);
2264
2265 // Emit the iterations count variable.
2266 // If it is not a variable, Sema decided to calculate iterations count on each
2267 // iteration (e.g., it is foldable into a constant).
2268 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2269 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2270 // Emit calculation of the iterations count.
2271 EmitIgnoredExpr(S.getCalcLastIteration());
2272 }
2273
2274 auto &RT = CGM.getOpenMPRuntime();
2275
2276 // Check pre-condition.
2277 {
2278 // Skip the entire loop if we don't meet the precondition.
2279 // If the condition constant folds and can be elided, avoid emitting the
2280 // whole loop.
2281 bool CondConstant;
2282 llvm::BasicBlock *ContBlock = nullptr;
2283 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2284 if (!CondConstant)
2285 return;
2286 } else {
2287 auto *ThenBlock = createBasicBlock("omp.precond.then");
2288 ContBlock = createBasicBlock("omp.precond.end");
2289 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2290 getProfileCount(&S));
2291 EmitBlock(ThenBlock);
2292 incrementProfileCounter(&S);
2293 }
2294
2295 // Emit 'then' code.
2296 {
2297 // Emit helper vars inits.
2298 LValue LB =
2299 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2300 LValue UB =
2301 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2302 LValue ST =
2303 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2304 LValue IL =
2305 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2306
2307 OMPPrivateScope LoopScope(*this);
2308 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
2309 S.private_counters());
2310 (void)LoopScope.Privatize();
2311
2312 // Detect the distribute schedule kind and chunk.
2313 llvm::Value *Chunk = nullptr;
2314 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2315 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2316 ScheduleKind = C->getDistScheduleKind();
2317 if (const auto *Ch = C->getChunkSize()) {
2318 Chunk = EmitScalarExpr(Ch);
2319 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2320 S.getIterationVariable()->getType(),
2321 S.getLocStart());
2322 }
2323 }
2324 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2325 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2326
2327 // OpenMP [2.10.8, distribute Construct, Description]
2328 // If dist_schedule is specified, kind must be static. If specified,
2329 // iterations are divided into chunks of size chunk_size, chunks are
2330 // assigned to the teams of the league in a round-robin fashion in the
2331 // order of the team number. When no chunk_size is specified, the
2332 // iteration space is divided into chunks that are approximately equal
2333 // in size, and at most one chunk is distributed to each team of the
2334 // league. The size of the chunks is unspecified in this case.
2335 if (RT.isStaticNonchunked(ScheduleKind,
2336 /* Chunked */ Chunk != nullptr)) {
2337 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2338 IVSize, IVSigned, /* Ordered = */ false,
2339 IL.getAddress(), LB.getAddress(),
2340 UB.getAddress(), ST.getAddress());
2341 auto LoopExit =
2342 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2343 // UB = min(UB, GlobalUB);
2344 EmitIgnoredExpr(S.getEnsureUpperBound());
2345 // IV = LB;
2346 EmitIgnoredExpr(S.getInit());
2347 // while (idx <= UB) { BODY; ++idx; }
2348 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2349 S.getInc(),
2350 [&S, LoopExit](CodeGenFunction &CGF) {
2351 CGF.EmitOMPLoopBody(S, LoopExit);
2352 CGF.EmitStopPoint(&S);
2353 },
2354 [](CodeGenFunction &) {});
2355 EmitBlock(LoopExit.getBlock());
2356 // Tell the runtime we are done.
2357 RT.emitForStaticFinish(*this, S.getLocStart());
2358 } else {
2359 // Emit the outer loop, which requests its work chunk [LB..UB] from
2360 // runtime and runs the inner loop to process it.
2361 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2362 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2363 IL.getAddress(), Chunk);
2364 }
2365 }
2366
2367 // We're now done with the loop, so jump to the continuation block.
2368 if (ContBlock) {
2369 EmitBranch(ContBlock);
2370 EmitBlock(ContBlock, true);
2371 }
2372 }
2373}
2374
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002375void CodeGenFunction::EmitOMPDistributeDirective(
2376 const OMPDistributeDirective &S) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002377 LexicalScope Scope(*this, S.getSourceRange());
2378 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2379 CGF.EmitOMPDistributeLoop(S);
2380 };
2381 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2382 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002383}
2384
Alexey Bataev5f600d62015-09-29 03:48:57 +00002385static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2386 const CapturedStmt *S) {
2387 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2388 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2389 CGF.CapturedStmtInfo = &CapStmtInfo;
2390 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2391 Fn->addFnAttr(llvm::Attribute::NoInline);
2392 return Fn;
2393}
2394
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002395void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002396 if (!S.getAssociatedStmt())
2397 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002398 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002399 auto *C = S.getSingleClause<OMPSIMDClause>();
2400 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2401 if (C) {
2402 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2403 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2404 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2405 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2406 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2407 } else {
2408 CGF.EmitStmt(
2409 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2410 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002411 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002412 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002413}
2414
Alexey Bataevb57056f2015-01-22 06:17:56 +00002415static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002416 QualType SrcType, QualType DestType,
2417 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002418 assert(CGF.hasScalarEvaluationKind(DestType) &&
2419 "DestType must have scalar evaluation kind.");
2420 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2421 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002422 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2423 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002424 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002425 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002426}
2427
2428static CodeGenFunction::ComplexPairTy
2429convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002430 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002431 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2432 "DestType must have complex evaluation kind.");
2433 CodeGenFunction::ComplexPairTy ComplexVal;
2434 if (Val.isScalar()) {
2435 // Convert the input element to the element type of the complex.
2436 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002437 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2438 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002439 ComplexVal = CodeGenFunction::ComplexPairTy(
2440 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2441 } else {
2442 assert(Val.isComplex() && "Must be a scalar or complex.");
2443 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2444 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2445 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002446 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002447 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002448 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002449 }
2450 return ComplexVal;
2451}
2452
Alexey Bataev5e018f92015-04-23 06:35:10 +00002453static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2454 LValue LVal, RValue RVal) {
2455 if (LVal.isGlobalReg()) {
2456 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2457 } else {
2458 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2459 : llvm::Monotonic,
2460 LVal.isVolatile(), /*IsInit=*/false);
2461 }
2462}
2463
Alexey Bataev8524d152016-01-21 12:35:58 +00002464void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2465 QualType RValTy, SourceLocation Loc) {
2466 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002467 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002468 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2469 *this, RVal, RValTy, LVal.getType(), Loc)),
2470 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002471 break;
2472 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002473 EmitStoreOfComplex(
2474 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002475 /*isInit=*/false);
2476 break;
2477 case TEK_Aggregate:
2478 llvm_unreachable("Must be a scalar or complex.");
2479 }
2480}
2481
Alexey Bataevb57056f2015-01-22 06:17:56 +00002482static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2483 const Expr *X, const Expr *V,
2484 SourceLocation Loc) {
2485 // v = x;
2486 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2487 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2488 LValue XLValue = CGF.EmitLValue(X);
2489 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002490 RValue Res = XLValue.isGlobalReg()
2491 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2492 : CGF.EmitAtomicLoad(XLValue, Loc,
2493 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002494 : llvm::Monotonic,
2495 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002496 // OpenMP, 2.12.6, atomic Construct
2497 // Any atomic construct with a seq_cst clause forces the atomically
2498 // performed operation to include an implicit flush operation without a
2499 // list.
2500 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002501 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002502 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002503}
2504
Alexey Bataevb8329262015-02-27 06:33:30 +00002505static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2506 const Expr *X, const Expr *E,
2507 SourceLocation Loc) {
2508 // x = expr;
2509 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002510 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002511 // OpenMP, 2.12.6, atomic Construct
2512 // Any atomic construct with a seq_cst clause forces the atomically
2513 // performed operation to include an implicit flush operation without a
2514 // list.
2515 if (IsSeqCst)
2516 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2517}
2518
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002519static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2520 RValue Update,
2521 BinaryOperatorKind BO,
2522 llvm::AtomicOrdering AO,
2523 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002524 auto &Context = CGF.CGM.getContext();
2525 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002526 // expression is simple and atomic is allowed for the given type for the
2527 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002528 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002529 !Update.getScalarVal()->getType()->isIntegerTy() ||
2530 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2531 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002532 X.getAddress().getElementType())) ||
2533 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002534 !Context.getTargetInfo().hasBuiltinAtomic(
2535 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002536 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002537
2538 llvm::AtomicRMWInst::BinOp RMWOp;
2539 switch (BO) {
2540 case BO_Add:
2541 RMWOp = llvm::AtomicRMWInst::Add;
2542 break;
2543 case BO_Sub:
2544 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002545 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002546 RMWOp = llvm::AtomicRMWInst::Sub;
2547 break;
2548 case BO_And:
2549 RMWOp = llvm::AtomicRMWInst::And;
2550 break;
2551 case BO_Or:
2552 RMWOp = llvm::AtomicRMWInst::Or;
2553 break;
2554 case BO_Xor:
2555 RMWOp = llvm::AtomicRMWInst::Xor;
2556 break;
2557 case BO_LT:
2558 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2559 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2560 : llvm::AtomicRMWInst::Max)
2561 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2562 : llvm::AtomicRMWInst::UMax);
2563 break;
2564 case BO_GT:
2565 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2566 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2567 : llvm::AtomicRMWInst::Min)
2568 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2569 : llvm::AtomicRMWInst::UMin);
2570 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002571 case BO_Assign:
2572 RMWOp = llvm::AtomicRMWInst::Xchg;
2573 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002574 case BO_Mul:
2575 case BO_Div:
2576 case BO_Rem:
2577 case BO_Shl:
2578 case BO_Shr:
2579 case BO_LAnd:
2580 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002581 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002582 case BO_PtrMemD:
2583 case BO_PtrMemI:
2584 case BO_LE:
2585 case BO_GE:
2586 case BO_EQ:
2587 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002588 case BO_AddAssign:
2589 case BO_SubAssign:
2590 case BO_AndAssign:
2591 case BO_OrAssign:
2592 case BO_XorAssign:
2593 case BO_MulAssign:
2594 case BO_DivAssign:
2595 case BO_RemAssign:
2596 case BO_ShlAssign:
2597 case BO_ShrAssign:
2598 case BO_Comma:
2599 llvm_unreachable("Unsupported atomic update operation");
2600 }
2601 auto *UpdateVal = Update.getScalarVal();
2602 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2603 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002604 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002605 X.getType()->hasSignedIntegerRepresentation());
2606 }
John McCall7f416cc2015-09-08 08:05:57 +00002607 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002608 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002609}
2610
Alexey Bataev5e018f92015-04-23 06:35:10 +00002611std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002612 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2613 llvm::AtomicOrdering AO, SourceLocation Loc,
2614 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2615 // Update expressions are allowed to have the following forms:
2616 // x binop= expr; -> xrval + expr;
2617 // x++, ++x -> xrval + 1;
2618 // x--, --x -> xrval - 1;
2619 // x = x binop expr; -> xrval binop expr
2620 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002621 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2622 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002623 if (X.isGlobalReg()) {
2624 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2625 // 'xrval'.
2626 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2627 } else {
2628 // Perform compare-and-swap procedure.
2629 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002630 }
2631 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002632 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002633}
2634
2635static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2636 const Expr *X, const Expr *E,
2637 const Expr *UE, bool IsXLHSInRHSPart,
2638 SourceLocation Loc) {
2639 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2640 "Update expr in 'atomic update' must be a binary operator.");
2641 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2642 // Update expressions are allowed to have the following forms:
2643 // x binop= expr; -> xrval + expr;
2644 // x++, ++x -> xrval + 1;
2645 // x--, --x -> xrval - 1;
2646 // x = x binop expr; -> xrval binop expr
2647 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002648 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002649 LValue XLValue = CGF.EmitLValue(X);
2650 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002651 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002652 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2653 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2654 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2655 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2656 auto Gen =
2657 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2658 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2659 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2660 return CGF.EmitAnyExpr(UE);
2661 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002662 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2663 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2664 // OpenMP, 2.12.6, atomic Construct
2665 // Any atomic construct with a seq_cst clause forces the atomically
2666 // performed operation to include an implicit flush operation without a
2667 // list.
2668 if (IsSeqCst)
2669 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2670}
2671
2672static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002673 QualType SourceType, QualType ResType,
2674 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002675 switch (CGF.getEvaluationKind(ResType)) {
2676 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002677 return RValue::get(
2678 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002679 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002680 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002681 return RValue::getComplex(Res.first, Res.second);
2682 }
2683 case TEK_Aggregate:
2684 break;
2685 }
2686 llvm_unreachable("Must be a scalar or complex.");
2687}
2688
2689static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2690 bool IsPostfixUpdate, const Expr *V,
2691 const Expr *X, const Expr *E,
2692 const Expr *UE, bool IsXLHSInRHSPart,
2693 SourceLocation Loc) {
2694 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2695 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2696 RValue NewVVal;
2697 LValue VLValue = CGF.EmitLValue(V);
2698 LValue XLValue = CGF.EmitLValue(X);
2699 RValue ExprRValue = CGF.EmitAnyExpr(E);
2700 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2701 QualType NewVValType;
2702 if (UE) {
2703 // 'x' is updated with some additional value.
2704 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2705 "Update expr in 'atomic capture' must be a binary operator.");
2706 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2707 // Update expressions are allowed to have the following forms:
2708 // x binop= expr; -> xrval + expr;
2709 // x++, ++x -> xrval + 1;
2710 // x--, --x -> xrval - 1;
2711 // x = x binop expr; -> xrval binop expr
2712 // x = expr Op x; - > expr binop xrval;
2713 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2714 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2715 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2716 NewVValType = XRValExpr->getType();
2717 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2718 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2719 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2720 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2721 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2722 RValue Res = CGF.EmitAnyExpr(UE);
2723 NewVVal = IsPostfixUpdate ? XRValue : Res;
2724 return Res;
2725 };
2726 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2727 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2728 if (Res.first) {
2729 // 'atomicrmw' instruction was generated.
2730 if (IsPostfixUpdate) {
2731 // Use old value from 'atomicrmw'.
2732 NewVVal = Res.second;
2733 } else {
2734 // 'atomicrmw' does not provide new value, so evaluate it using old
2735 // value of 'x'.
2736 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2737 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2738 NewVVal = CGF.EmitAnyExpr(UE);
2739 }
2740 }
2741 } else {
2742 // 'x' is simply rewritten with some 'expr'.
2743 NewVValType = X->getType().getNonReferenceType();
2744 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002745 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002746 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2747 NewVVal = XRValue;
2748 return ExprRValue;
2749 };
2750 // Try to perform atomicrmw xchg, otherwise simple exchange.
2751 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2752 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2753 Loc, Gen);
2754 if (Res.first) {
2755 // 'atomicrmw' instruction was generated.
2756 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2757 }
2758 }
2759 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002760 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002761 // OpenMP, 2.12.6, atomic Construct
2762 // Any atomic construct with a seq_cst clause forces the atomically
2763 // performed operation to include an implicit flush operation without a
2764 // list.
2765 if (IsSeqCst)
2766 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2767}
2768
Alexey Bataevb57056f2015-01-22 06:17:56 +00002769static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002770 bool IsSeqCst, bool IsPostfixUpdate,
2771 const Expr *X, const Expr *V, const Expr *E,
2772 const Expr *UE, bool IsXLHSInRHSPart,
2773 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002774 switch (Kind) {
2775 case OMPC_read:
2776 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2777 break;
2778 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002779 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2780 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002781 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002782 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002783 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2784 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002785 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002786 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2787 IsXLHSInRHSPart, Loc);
2788 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002789 case OMPC_if:
2790 case OMPC_final:
2791 case OMPC_num_threads:
2792 case OMPC_private:
2793 case OMPC_firstprivate:
2794 case OMPC_lastprivate:
2795 case OMPC_reduction:
2796 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002797 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002798 case OMPC_collapse:
2799 case OMPC_default:
2800 case OMPC_seq_cst:
2801 case OMPC_shared:
2802 case OMPC_linear:
2803 case OMPC_aligned:
2804 case OMPC_copyin:
2805 case OMPC_copyprivate:
2806 case OMPC_flush:
2807 case OMPC_proc_bind:
2808 case OMPC_schedule:
2809 case OMPC_ordered:
2810 case OMPC_nowait:
2811 case OMPC_untied:
2812 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002813 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002814 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002815 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002816 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002817 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002818 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002819 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002820 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002821 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002822 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002823 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002824 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002825 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002826 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002827 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002828 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2829 }
2830}
2831
2832void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002833 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002834 OpenMPClauseKind Kind = OMPC_unknown;
2835 for (auto *C : S.clauses()) {
2836 // Find first clause (skip seq_cst clause, if it is first).
2837 if (C->getClauseKind() != OMPC_seq_cst) {
2838 Kind = C->getClauseKind();
2839 break;
2840 }
2841 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002842
2843 const auto *CS =
2844 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002845 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002846 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002847 }
2848 // Processing for statements under 'atomic capture'.
2849 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2850 for (const auto *C : Compound->body()) {
2851 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2852 enterFullExpression(EWC);
2853 }
2854 }
2855 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002856
Alexey Bataev3392d762016-02-16 11:18:12 +00002857 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002858 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2859 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002860 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2861 S.getV(), S.getExpr(), S.getUpdateExpr(),
2862 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002863 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002864 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002865}
2866
Samuel Antaobed3c462015-10-02 16:14:20 +00002867void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002868 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002869 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2870
2871 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002872 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002873
Samuel Antaoee8fb302016-01-06 13:42:12 +00002874 llvm::Function *Fn = nullptr;
2875 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002876
2877 // Check if we have any if clause associated with the directive.
2878 const Expr *IfCond = nullptr;
2879
2880 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2881 IfCond = C->getCondition();
2882 }
2883
2884 // Check if we have any device clause associated with the directive.
2885 const Expr *Device = nullptr;
2886 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2887 Device = C->getDevice();
2888 }
2889
Samuel Antaoee8fb302016-01-06 13:42:12 +00002890 // Check if we have an if clause whose conditional always evaluates to false
2891 // or if we do not have any targets specified. If so the target region is not
2892 // an offload entry point.
2893 bool IsOffloadEntry = true;
2894 if (IfCond) {
2895 bool Val;
2896 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2897 IsOffloadEntry = false;
2898 }
2899 if (CGM.getLangOpts().OMPTargetTriples.empty())
2900 IsOffloadEntry = false;
2901
2902 assert(CurFuncDecl && "No parent declaration for target region!");
2903 StringRef ParentName;
2904 // In case we have Ctors/Dtors we use the complete type variant to produce
2905 // the mangling of the device outlined kernel.
2906 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2907 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2908 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2909 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2910 else
2911 ParentName =
2912 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2913
2914 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2915 IsOffloadEntry);
2916
2917 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002918 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002919}
2920
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002921static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
2922 const OMPExecutableDirective &S,
2923 OpenMPDirectiveKind InnermostKind,
2924 const RegionCodeGenTy &CodeGen) {
2925 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2926 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2927 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2928 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
2929 emitParallelOrTeamsOutlinedFunction(S,
2930 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00002931
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002932 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
2933 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
2934 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
2935 if (NT || TL) {
2936 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
2937 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
2938 /* isSigned = */ true) :
2939 CGF.Builder.getInt32(0);
2940
2941 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
2942 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
2943 /* isSigned = */ true) :
2944 CGF.Builder.getInt32(0);
2945
2946 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
2947 ThreadLimitVal, S.getLocStart());
2948 }
2949
2950 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
2951 CapturedVars);
2952}
2953
2954void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
2955 LexicalScope Scope(*this, S.getSourceRange());
2956 // Emit parallel region as a standalone region.
2957 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2958 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00002959 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
2960 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002961 (void)PrivateScope.Privatize();
2962 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2963 };
2964 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002965}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002966
2967void CodeGenFunction::EmitOMPCancellationPointDirective(
2968 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002969 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2970 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002971}
2972
Alexey Bataev80909872015-07-02 11:25:17 +00002973void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002974 const Expr *IfCond = nullptr;
2975 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2976 if (C->getNameModifier() == OMPD_unknown ||
2977 C->getNameModifier() == OMPD_cancel) {
2978 IfCond = C->getCondition();
2979 break;
2980 }
2981 }
2982 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002983 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002984}
2985
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002986CodeGenFunction::JumpDest
2987CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2988 if (Kind == OMPD_parallel || Kind == OMPD_task)
2989 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002990 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002991 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002992 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002993}
Michael Wong65f367f2015-07-21 13:44:28 +00002994
2995// Generate the instructions for '#pragma omp target data' directive.
2996void CodeGenFunction::EmitOMPTargetDataDirective(
2997 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002998 // emit the code inside the construct for now
2999 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00003000 CGM.getOpenMPRuntime().emitInlinedDirective(
3001 *this, OMPD_target_data,
3002 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00003003}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003004
Samuel Antaodf67fc42016-01-19 19:15:56 +00003005void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3006 const OMPTargetEnterDataDirective &S) {
3007 // TODO: codegen for target enter data.
3008}
3009
Samuel Antao72590762016-01-19 20:04:50 +00003010void CodeGenFunction::EmitOMPTargetExitDataDirective(
3011 const OMPTargetExitDataDirective &S) {
3012 // TODO: codegen for target exit data.
3013}
3014
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003015void CodeGenFunction::EmitOMPTargetParallelDirective(
3016 const OMPTargetParallelDirective &S) {
3017 // TODO: codegen for target parallel.
3018}
3019
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003020void CodeGenFunction::EmitOMPTargetParallelForDirective(
3021 const OMPTargetParallelForDirective &S) {
3022 // TODO: codegen for target parallel for.
3023}
3024
Alexey Bataev49f6e782015-12-01 04:18:41 +00003025void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
3026 // emit the code inside the construct for now
3027 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3028 CGM.getOpenMPRuntime().emitInlinedDirective(
3029 *this, OMPD_taskloop,
3030 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
3031}
3032
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003033void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3034 const OMPTaskLoopSimdDirective &S) {
3035 // emit the code inside the construct for now
3036 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3037 CGM.getOpenMPRuntime().emitInlinedDirective(
3038 *this, OMPD_taskloop_simd,
3039 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
3040}
3041