blob: 45f07a8406fe10bbdae1f49b3c4e28ccd4a66434 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
Alexey Bataev6a71f362017-08-22 17:54:52 +000068 assert(VD == VD->getCanonicalDecl() &&
69 "Canonical decl must be captured.");
Alexey Bataev4ba78a42016-04-27 07:56:03 +000070 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71 isCapturedVar(CGF, VD) ||
72 (CGF.CapturedStmtInfo &&
73 InlinedShareds.isGlobalVarCaptured(VD)),
74 VD->getType().getNonReferenceType(), VK_LValue,
75 SourceLocation());
76 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77 return CGF.EmitLValue(&DRE).getAddress();
78 });
79 }
80 }
81 (void)InlinedShareds.Privatize();
82 }
83 }
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99 : OMPLexicalScope(CGF, S,
100 /*AsInlined=*/false,
101 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
115 : OMPLexicalScope(CGF, S,
116 /*AsInlined=*/false,
117 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
118};
119
Alexey Bataev5a3af132016-03-29 08:58:54 +0000120/// Private scope for OpenMP loop-based directives, that supports capturing
121/// of used expression from loop statement.
122class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
124 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
125 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
126 for (const auto *I : PreInits->decls())
127 CGF.EmitVarDecl(cast<VarDecl>(*I));
128 }
129 }
130 }
131
132public:
133 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
134 : CodeGenFunction::RunCleanupsScope(CGF) {
135 emitPreInitStmt(CGF, S);
136 }
137};
138
Alexey Bataev3392d762016-02-16 11:18:12 +0000139} // namespace
140
Alexey Bataevf8365372017-11-17 17:57:25 +0000141static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
142 const OMPExecutableDirective &S,
143 const RegionCodeGenTy &CodeGen);
144
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000145LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
146 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
147 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
148 OrigVD = OrigVD->getCanonicalDecl();
149 bool IsCaptured =
150 LambdaCaptureFields.lookup(OrigVD) ||
151 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
152 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
153 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
154 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
155 return EmitLValue(&DRE);
156 }
157 }
158 return EmitLValue(E);
159}
160
Alexey Bataev1189bd02016-01-26 12:20:39 +0000161llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
162 auto &C = getContext();
163 llvm::Value *Size = nullptr;
164 auto SizeInChars = C.getTypeSizeInChars(Ty);
165 if (SizeInChars.isZero()) {
166 // getTypeSizeInChars() returns 0 for a VLA.
167 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
168 llvm::Value *ArraySize;
169 std::tie(ArraySize, Ty) = getVLASize(VAT);
170 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
171 }
172 SizeInChars = C.getTypeSizeInChars(Ty);
173 if (SizeInChars.isZero())
174 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
175 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
176 } else
177 Size = CGM.getSize(SizeInChars);
178 return Size;
179}
180
Alexey Bataev2377fe92015-09-10 08:12:02 +0000181void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000182 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000183 const RecordDecl *RD = S.getCapturedRecordDecl();
184 auto CurField = RD->field_begin();
185 auto CurCap = S.captures().begin();
186 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
187 E = S.capture_init_end();
188 I != E; ++I, ++CurField, ++CurCap) {
189 if (CurField->hasCapturedVLAType()) {
190 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000191 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000192 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000193 } else if (CurCap->capturesThis())
194 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000195 else if (CurCap->capturesVariableByCopy()) {
196 llvm::Value *CV =
197 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
198
199 // If the field is not a pointer, we need to save the actual value
200 // and load it as a void pointer.
201 if (!CurField->getType()->isAnyPointerType()) {
202 auto &Ctx = getContext();
203 auto DstAddr = CreateMemTemp(
204 Ctx.getUIntPtrType(),
205 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
206 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
207
208 auto *SrcAddrVal = EmitScalarConversion(
209 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
210 Ctx.getPointerType(CurField->getType()), SourceLocation());
211 LValue SrcLV =
212 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
213
214 // Store the value using the source type pointer.
215 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
216
217 // Load the value using the destination type pointer.
218 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
219 }
220 CapturedVars.push_back(CV);
221 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000222 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000223 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000225 }
226}
227
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000228static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
229 StringRef Name, LValue AddrLV,
230 bool isReferenceType = false) {
231 ASTContext &Ctx = CGF.getContext();
232
233 auto *CastedPtr = CGF.EmitScalarConversion(
234 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
235 Ctx.getPointerType(DstType), SourceLocation());
236 auto TmpAddr =
237 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
238 .getAddress();
239
240 // If we are dealing with references we need to return the address of the
241 // reference instead of the reference of the value.
242 if (isReferenceType) {
243 QualType RefType = Ctx.getLValueReferenceType(DstType);
244 auto *RefVal = TmpAddr.getPointer();
245 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
246 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000247 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000248 }
249
250 return TmpAddr;
251}
252
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000253static QualType getCanonicalParamType(ASTContext &C, QualType T) {
254 if (T->isLValueReferenceType()) {
255 return C.getLValueReferenceType(
256 getCanonicalParamType(C, T.getNonReferenceType()),
257 /*SpelledAsLValue=*/false);
258 }
259 if (T->isPointerType())
260 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000261 if (auto *A = T->getAsArrayTypeUnsafe()) {
262 if (auto *VLA = dyn_cast<VariableArrayType>(A))
263 return getCanonicalParamType(C, VLA->getElementType());
264 else if (!A->isVariablyModifiedType())
265 return C.getCanonicalType(T);
266 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000267 return C.getCanonicalParamType(T);
268}
269
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000270namespace {
271 /// Contains required data for proper outlined function codegen.
272 struct FunctionOptions {
273 /// Captured statement for which the function is generated.
274 const CapturedStmt *S = nullptr;
275 /// true if cast to/from UIntPtr is required for variables captured by
276 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000277 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000278 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000279 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000280 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000281 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000282 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000283 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
284 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000285 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000286 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
287 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000288 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 };
290}
291
Alexey Bataeve754b182017-08-09 19:38:53 +0000292static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000293 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000294 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000295 &LocalAddrs,
296 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
297 &VLASizes,
298 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
299 const CapturedDecl *CD = FO.S->getCapturedDecl();
300 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000301 assert(CD->hasBody() && "missing CapturedDecl body");
302
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000303 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000304 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000305 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000306 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000307 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000308 Args.append(CD->param_begin(),
309 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000310 TargetArgs.append(
311 CD->param_begin(),
312 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000313 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 for (auto *FD : RD->fields()) {
315 QualType ArgType = FD->getType();
316 IdentifierInfo *II = nullptr;
317 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000318
319 // If this is a capture by copy and the type is not a pointer, the outlined
320 // function argument type should be uintptr and the value properly casted to
321 // uintptr. This is necessary given that the runtime library is only able to
322 // deal with pointers. We can pass in the same way the VLA type sizes to the
323 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000324 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000325 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000326 if (FO.UIntPtrCastRequired)
327 ArgType = Ctx.getUIntPtrType();
328 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000329
330 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000331 CapVar = I->getCapturedVar();
332 II = CapVar->getIdentifier();
333 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000334 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000335 else {
336 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000337 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000338 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000339 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000340 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000341 auto *Arg =
342 ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II,
343 ArgType, ImplicitParamDecl::Other);
344 Args.emplace_back(Arg);
345 // Do not cast arguments if we emit function with non-original types.
346 TargetArgs.emplace_back(
347 FO.UIntPtrCastRequired
348 ? Arg
349 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000350 ++I;
351 }
352 Args.append(
353 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
354 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000355 TargetArgs.append(
356 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
357 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000358
359 // Create the function declaration.
360 FunctionType::ExtInfo ExtInfo;
361 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000362 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000363 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
364
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000365 llvm::Function *F =
366 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
367 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000368 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
369 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000370 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371
372 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000373 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
374 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000375 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000378 // Do not map arguments if we emit function with non-original types.
379 Address LocalAddr(Address::invalid());
380 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
381 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
382 TargetArgs[Cnt]);
383 } else {
384 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
385 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000386 // If we are capturing a pointer by copy we don't need to do anything, just
387 // use the value that we get from the arguments.
388 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000389 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000390 // If the variable is a reference we need to materialize it here.
391 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000392 Address RefAddr = CGF.CreateMemTemp(
393 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
394 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
395 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000396 LocalAddr = RefAddr;
397 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000398 if (!FO.RegisterCastedArgsOnly)
399 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000400 ++Cnt;
401 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000402 continue;
403 }
404
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000405 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
406 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000407 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 if (FO.UIntPtrCastRequired) {
409 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
410 Args[Cnt]->getName(),
411 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000412 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000413 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000414 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 } else if (I->capturesVariable()) {
419 auto *Var = I->getCapturedVar();
420 QualType VarTy = Var->getType();
421 Address ArgAddr = ArgLVal.getAddress();
422 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000423 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000424 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000425 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000426 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000427 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000428 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
429 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000430 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000431 if (!FO.RegisterCastedArgsOnly) {
432 LocalAddrs.insert(
433 {Args[Cnt],
434 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
435 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000436 } else if (I->capturesVariableByCopy()) {
437 assert(!FD->getType()->isAnyPointerType() &&
438 "Not expecting a captured pointer.");
439 auto *Var = I->getCapturedVar();
440 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000441 LocalAddrs.insert(
442 {Args[Cnt],
443 {Var,
444 FO.UIntPtrCastRequired
445 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
446 ArgLVal, VarTy->isReferenceType())
447 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000448 } else {
449 // If 'this' is captured, load it into CXXThisValue.
450 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000451 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
452 .getScalarVal();
453 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000454 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000455 ++Cnt;
456 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000457 }
458
Alexey Bataeve754b182017-08-09 19:38:53 +0000459 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000460}
461
462llvm::Function *
463CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
464 assert(
465 CapturedStmtInfo &&
466 "CapturedStmtInfo should be set when generating the captured function");
467 const CapturedDecl *CD = S.getCapturedDecl();
468 // Build the argument list.
469 bool NeedWrapperFunction =
470 getDebugInfo() &&
471 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
472 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000473 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000474 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000475 SmallString<256> Buffer;
476 llvm::raw_svector_ostream Out(Buffer);
477 Out << CapturedStmtInfo->getHelperName();
478 if (NeedWrapperFunction)
479 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000480 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000481 Out.str());
482 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
483 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000484 for (const auto &LocalAddrPair : LocalAddrs) {
485 if (LocalAddrPair.second.first) {
486 setAddrOfLocalVar(LocalAddrPair.second.first,
487 LocalAddrPair.second.second);
488 }
489 }
490 for (const auto &VLASizePair : VLASizes)
491 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000492 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000493 CapturedStmtInfo->EmitBody(*this, CD->getBody());
494 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000495 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000496 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000497
Alexey Bataevefd884d2017-08-04 21:26:25 +0000498 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000499 /*RegisterCastedArgsOnly=*/true,
500 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000502 Args.clear();
503 LocalAddrs.clear();
504 VLASizes.clear();
505 llvm::Function *WrapperF =
506 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000507 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000508 llvm::SmallVector<llvm::Value *, 4> CallArgs;
509 for (const auto *Arg : Args) {
510 llvm::Value *CallArg;
511 auto I = LocalAddrs.find(Arg);
512 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000513 LValue LV = WrapperCGF.MakeAddrLValue(
514 I->second.second,
515 I->second.first ? I->second.first->getType() : Arg->getType(),
516 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000517 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
518 } else {
519 auto EI = VLASizes.find(Arg);
520 if (EI != VLASizes.end())
521 CallArg = EI->second.second;
522 else {
523 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000524 Arg->getType(),
525 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000526 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
527 }
528 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000529 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000531 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
532 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000533 WrapperCGF.FinishFunction();
534 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000535}
536
Alexey Bataev9959db52014-05-06 10:08:46 +0000537//===----------------------------------------------------------------------===//
538// OpenMP Directive Emission
539//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000540void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address DestAddr, Address SrcAddr, QualType OriginalType,
542 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000543 // Perform element-by-element initialization.
544 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000545
546 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000547 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000548 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
549 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
550
551 auto SrcBegin = SrcAddr.getPointer();
552 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000553 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000554 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
555 // The basic structure here is a while-do loop.
556 auto BodyBB = createBasicBlock("omp.arraycpy.body");
557 auto DoneBB = createBasicBlock("omp.arraycpy.done");
558 auto IsEmpty =
559 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
560 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000561
Alexey Bataev420d45b2015-04-14 05:11:24 +0000562 // Enter the loop body, making that address the current address.
563 auto EntryBB = Builder.GetInsertBlock();
564 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000565
566 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
567
568 llvm::PHINode *SrcElementPHI =
569 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
570 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
571 Address SrcElementCurrent =
572 Address(SrcElementPHI,
573 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
574
575 llvm::PHINode *DestElementPHI =
576 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
577 DestElementPHI->addIncoming(DestBegin, EntryBB);
578 Address DestElementCurrent =
579 Address(DestElementPHI,
580 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000581
Alexey Bataev420d45b2015-04-14 05:11:24 +0000582 // Emit copy.
583 CopyGen(DestElementCurrent, SrcElementCurrent);
584
585 // Shift the address forward by one element.
586 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000587 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000588 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000589 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000590 // Check whether we've reached the end.
591 auto Done =
592 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
593 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000594 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
595 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000596
597 // Done.
598 EmitBlock(DoneBB, /*IsFinished=*/true);
599}
600
John McCall7f416cc2015-09-08 08:05:57 +0000601void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
602 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000603 const VarDecl *SrcVD, const Expr *Copy) {
604 if (OriginalType->isArrayType()) {
605 auto *BO = dyn_cast<BinaryOperator>(Copy);
606 if (BO && BO->getOpcode() == BO_Assign) {
607 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000608 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000609 } else {
610 // For arrays with complex element types perform element by element
611 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000612 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000613 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000614 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000615 // Working with the single array element, so have to remap
616 // destination and source variables to corresponding array
617 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000618 CodeGenFunction::OMPPrivateScope Remap(*this);
619 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000620 return DestElement;
621 });
622 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000623 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000624 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000625 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000626 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000627 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628 } else {
629 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000630 CodeGenFunction::OMPPrivateScope Remap(*this);
631 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
632 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000633 (void)Remap.Privatize();
634 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000635 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000636 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000637}
638
Alexey Bataev69c62a92015-04-15 04:52:20 +0000639bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
640 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000641 if (!HaveInsertPoint())
642 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000643 bool FirstprivateIsLastprivate = false;
644 llvm::DenseSet<const VarDecl *> Lastprivates;
645 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
646 for (const auto *D : C->varlists())
647 Lastprivates.insert(
648 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
649 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000650 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000651 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000652 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000653 auto IRef = C->varlist_begin();
654 auto InitsRef = C->inits().begin();
655 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000656 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000657 bool ThisFirstprivateIsLastprivate =
658 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000659 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000660 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000661 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000662 !FD->getType()->isReferenceType()) {
663 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
664 ++IRef;
665 ++InitsRef;
666 continue;
667 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000668 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000670 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000671 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
672 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
673 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000674 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
675 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
676 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000677 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000678 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000679 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000680 // Emit VarDecl with copy init for arrays.
681 // Get the address of the original variable captured in current
682 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000683 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000684 auto Emission = EmitAutoVarAlloca(*VD);
685 auto *Init = VD->getInit();
686 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
687 // Perform simple memcpy.
688 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000689 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000690 } else {
691 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000692 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000693 [this, VDInit, Init](Address DestElement,
694 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000695 // Clean up any temporaries needed by the initialization.
696 RunCleanupsScope InitScope(*this);
697 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000698 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000699 EmitAnyExprToMem(Init, DestElement,
700 Init->getType().getQualifiers(),
701 /*IsInitializer*/ false);
702 LocalDeclMap.erase(VDInit);
703 });
704 }
705 EmitAutoVarCleanups(Emission);
706 return Emission.getAllocatedAddress();
707 });
708 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000709 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000710 // Emit private VarDecl with copy init.
711 // Remap temp VDInit variable to the address of the original
712 // variable
713 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000714 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000715 EmitDecl(*VD);
716 LocalDeclMap.erase(VDInit);
717 return GetAddrOfLocalVar(VD);
718 });
719 }
720 assert(IsRegistered &&
721 "firstprivate var already registered as private");
722 // Silence the warning about unused variable.
723 (void)IsRegistered;
724 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000725 ++IRef;
726 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000727 }
728 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000729 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000730}
731
Alexey Bataev03b340a2014-10-21 03:16:40 +0000732void CodeGenFunction::EmitOMPPrivateClause(
733 const OMPExecutableDirective &D,
734 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000735 if (!HaveInsertPoint())
736 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000737 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000738 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000739 auto IRef = C->varlist_begin();
740 for (auto IInit : C->private_copies()) {
741 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000742 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
743 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
744 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000745 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000746 // Emit private VarDecl with copy init.
747 EmitDecl(*VD);
748 return GetAddrOfLocalVar(VD);
749 });
750 assert(IsRegistered && "private var already registered as private");
751 // Silence the warning about unused variable.
752 (void)IsRegistered;
753 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000754 ++IRef;
755 }
756 }
757}
758
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000759bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000760 if (!HaveInsertPoint())
761 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000762 // threadprivate_var1 = master_threadprivate_var1;
763 // operator=(threadprivate_var2, master_threadprivate_var2);
764 // ...
765 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000766 llvm::DenseSet<const VarDecl *> CopiedVars;
767 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000768 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000769 auto IRef = C->varlist_begin();
770 auto ISrcRef = C->source_exprs().begin();
771 auto IDestRef = C->destination_exprs().begin();
772 for (auto *AssignOp : C->assignment_ops()) {
773 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000774 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000775 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000776 // Get the address of the master variable. If we are emitting code with
777 // TLS support, the address is passed from the master as field in the
778 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000779 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000780 if (getLangOpts().OpenMPUseTLS &&
781 getContext().getTargetInfo().isTLSSupported()) {
782 assert(CapturedStmtInfo->lookup(VD) &&
783 "Copyin threadprivates should have been captured!");
784 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
785 VK_LValue, (*IRef)->getExprLoc());
786 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000787 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000788 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000789 MasterAddr =
790 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
791 : CGM.GetAddrOfGlobal(VD),
792 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000793 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000794 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000795 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000796 if (CopiedVars.size() == 1) {
797 // At first check if current thread is a master thread. If it is, no
798 // need to copy data.
799 CopyBegin = createBasicBlock("copyin.not.master");
800 CopyEnd = createBasicBlock("copyin.not.master.end");
801 Builder.CreateCondBr(
802 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000803 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
804 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000805 CopyBegin, CopyEnd);
806 EmitBlock(CopyBegin);
807 }
808 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
809 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000810 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000811 }
812 ++IRef;
813 ++ISrcRef;
814 ++IDestRef;
815 }
816 }
817 if (CopyEnd) {
818 // Exit out of copying procedure for non-master thread.
819 EmitBlock(CopyEnd, /*IsFinished=*/true);
820 return true;
821 }
822 return false;
823}
824
Alexey Bataev38e89532015-04-16 04:54:05 +0000825bool CodeGenFunction::EmitOMPLastprivateClauseInit(
826 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000827 if (!HaveInsertPoint())
828 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000829 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000830 llvm::DenseSet<const VarDecl *> SIMDLCVs;
831 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
832 auto *LoopDirective = cast<OMPLoopDirective>(&D);
833 for (auto *C : LoopDirective->counters()) {
834 SIMDLCVs.insert(
835 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
836 }
837 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000838 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000839 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000840 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000841 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
842 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000843 auto IRef = C->varlist_begin();
844 auto IDestRef = C->destination_exprs().begin();
845 for (auto *IInit : C->private_copies()) {
846 // Keep the address of the original variable for future update at the end
847 // of the loop.
848 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000849 // Taskloops do not require additional initialization, it is done in
850 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000851 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
852 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000853 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000854 DeclRefExpr DRE(
855 const_cast<VarDecl *>(OrigVD),
856 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
857 OrigVD) != nullptr,
858 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
859 return EmitLValue(&DRE).getAddress();
860 });
861 // Check if the variable is also a firstprivate: in this case IInit is
862 // not generated. Initialization of this variable will happen in codegen
863 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000864 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000865 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000866 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
867 // Emit private VarDecl with copy init.
868 EmitDecl(*VD);
869 return GetAddrOfLocalVar(VD);
870 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000871 assert(IsRegistered &&
872 "lastprivate var already registered as private");
873 (void)IsRegistered;
874 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000875 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000876 ++IRef;
877 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000878 }
879 }
880 return HasAtLeastOneLastprivate;
881}
882
883void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000884 const OMPExecutableDirective &D, bool NoFinals,
885 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000886 if (!HaveInsertPoint())
887 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000888 // Emit following code:
889 // if (<IsLastIterCond>) {
890 // orig_var1 = private_orig_var1;
891 // ...
892 // orig_varn = private_orig_varn;
893 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000894 llvm::BasicBlock *ThenBB = nullptr;
895 llvm::BasicBlock *DoneBB = nullptr;
896 if (IsLastIterCond) {
897 ThenBB = createBasicBlock(".omp.lastprivate.then");
898 DoneBB = createBasicBlock(".omp.lastprivate.done");
899 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
900 EmitBlock(ThenBB);
901 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000902 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
903 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000904 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000905 auto IC = LoopDirective->counters().begin();
906 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000907 auto *D =
908 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
909 if (NoFinals)
910 AlreadyEmittedVars.insert(D);
911 else
912 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000913 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000914 }
915 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000916 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
917 auto IRef = C->varlist_begin();
918 auto ISrcRef = C->source_exprs().begin();
919 auto IDestRef = C->destination_exprs().begin();
920 for (auto *AssignOp : C->assignment_ops()) {
921 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
922 QualType Type = PrivateVD->getType();
923 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
924 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
925 // If lastprivate variable is a loop control variable for loop-based
926 // directive, update its value before copyin back to original
927 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000928 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
929 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000930 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
931 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
932 // Get the address of the original variable.
933 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
934 // Get the address of the private variable.
935 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
936 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
937 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000938 Address(Builder.CreateLoad(PrivateAddr),
939 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000940 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000941 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000942 ++IRef;
943 ++ISrcRef;
944 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000945 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000946 if (auto *PostUpdate = C->getPostUpdateExpr())
947 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000948 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000949 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000950 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000951}
952
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000953void CodeGenFunction::EmitOMPReductionClauseInit(
954 const OMPExecutableDirective &D,
955 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000956 if (!HaveInsertPoint())
957 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000958 SmallVector<const Expr *, 4> Shareds;
959 SmallVector<const Expr *, 4> Privates;
960 SmallVector<const Expr *, 4> ReductionOps;
961 SmallVector<const Expr *, 4> LHSs;
962 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000963 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000964 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000965 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000966 auto ILHS = C->lhs_exprs().begin();
967 auto IRHS = C->rhs_exprs().begin();
968 for (const auto *Ref : C->varlists()) {
969 Shareds.emplace_back(Ref);
970 Privates.emplace_back(*IPriv);
971 ReductionOps.emplace_back(*IRed);
972 LHSs.emplace_back(*ILHS);
973 RHSs.emplace_back(*IRHS);
974 std::advance(IPriv, 1);
975 std::advance(IRed, 1);
976 std::advance(ILHS, 1);
977 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000978 }
979 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
981 unsigned Count = 0;
982 auto ILHS = LHSs.begin();
983 auto IRHS = RHSs.begin();
984 auto IPriv = Privates.begin();
985 for (const auto *IRef : Shareds) {
986 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
987 // Emit private VarDecl with reduction init.
988 RedCG.emitSharedLValue(*this, Count);
989 RedCG.emitAggregateType(*this, Count);
990 auto Emission = EmitAutoVarAlloca(*PrivateVD);
991 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
992 RedCG.getSharedLValue(Count),
993 [&Emission](CodeGenFunction &CGF) {
994 CGF.EmitAutoVarInit(Emission);
995 return true;
996 });
997 EmitAutoVarCleanups(Emission);
998 Address BaseAddr = RedCG.adjustPrivateAddress(
999 *this, Count, Emission.getAllocatedAddress());
1000 bool IsRegistered = PrivateScope.addPrivate(
1001 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1002 assert(IsRegistered && "private var already registered as private");
1003 // Silence the warning about unused variable.
1004 (void)IsRegistered;
1005
1006 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1007 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001008 QualType Type = PrivateVD->getType();
1009 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1010 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001011 // Store the address of the original variable associated with the LHS
1012 // implicit variable.
1013 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1014 return RedCG.getSharedLValue(Count).getAddress();
1015 });
1016 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1017 return GetAddrOfLocalVar(PrivateVD);
1018 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001019 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1020 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001021 // Store the address of the original variable associated with the LHS
1022 // implicit variable.
1023 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1024 return RedCG.getSharedLValue(Count).getAddress();
1025 });
1026 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1027 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1028 ConvertTypeForMem(RHSVD->getType()),
1029 "rhs.begin");
1030 });
1031 } else {
1032 QualType Type = PrivateVD->getType();
1033 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1034 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1035 // Store the address of the original variable associated with the LHS
1036 // implicit variable.
1037 if (IsArray) {
1038 OriginalAddr = Builder.CreateElementBitCast(
1039 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1040 }
1041 PrivateScope.addPrivate(
1042 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1043 PrivateScope.addPrivate(
1044 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1045 return IsArray
1046 ? Builder.CreateElementBitCast(
1047 GetAddrOfLocalVar(PrivateVD),
1048 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1049 : GetAddrOfLocalVar(PrivateVD);
1050 });
1051 }
1052 ++ILHS;
1053 ++IRHS;
1054 ++IPriv;
1055 ++Count;
1056 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001057}
1058
1059void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001060 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001061 if (!HaveInsertPoint())
1062 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001063 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001064 llvm::SmallVector<const Expr *, 8> LHSExprs;
1065 llvm::SmallVector<const Expr *, 8> RHSExprs;
1066 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001067 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001068 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001069 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001070 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001071 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1072 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1073 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1074 }
1075 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001076 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1077 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1078 D.getDirectiveKind() == OMPD_simd;
1079 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001080 // Emit nowait reduction if nowait clause is present or directive is a
1081 // parallel directive (it always has implicit barrier).
1082 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001083 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001084 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001085 }
1086}
1087
Alexey Bataev61205072016-03-02 04:57:40 +00001088static void emitPostUpdateForReductionClause(
1089 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1090 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1091 if (!CGF.HaveInsertPoint())
1092 return;
1093 llvm::BasicBlock *DoneBB = nullptr;
1094 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1095 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1096 if (!DoneBB) {
1097 if (auto *Cond = CondGen(CGF)) {
1098 // If the first post-update expression is found, emit conditional
1099 // block if it was requested.
1100 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1101 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1102 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1103 CGF.EmitBlock(ThenBB);
1104 }
1105 }
1106 CGF.EmitIgnoredExpr(PostUpdate);
1107 }
1108 }
1109 if (DoneBB)
1110 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1111}
1112
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001113namespace {
1114/// Codegen lambda for appending distribute lower and upper bounds to outlined
1115/// parallel function. This is necessary for combined constructs such as
1116/// 'distribute parallel for'
1117typedef llvm::function_ref<void(CodeGenFunction &,
1118 const OMPExecutableDirective &,
1119 llvm::SmallVectorImpl<llvm::Value *> &)>
1120 CodeGenBoundParametersTy;
1121} // anonymous namespace
1122
1123static void emitCommonOMPParallelDirective(
1124 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1125 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1126 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001127 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1128 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1129 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001130 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001131 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001132 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1133 /*IgnoreResultAssign*/ true);
1134 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1135 CGF, NumThreads, NumThreadsClause->getLocStart());
1136 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001137 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001138 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001139 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1140 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1141 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001142 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001143 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1144 if (C->getNameModifier() == OMPD_unknown ||
1145 C->getNameModifier() == OMPD_parallel) {
1146 IfCond = C->getCondition();
1147 break;
1148 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001149 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001150
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001151 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001152 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001153 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1154 // lower and upper bounds with the pragma 'for' chunking mechanism.
1155 // The following lambda takes care of appending the lower and upper bound
1156 // parameters when necessary
1157 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001158 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001159 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001160 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001161}
1162
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001163static void emitEmptyBoundParameters(CodeGenFunction &,
1164 const OMPExecutableDirective &,
1165 llvm::SmallVectorImpl<llvm::Value *> &) {}
1166
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001168 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001169 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001171 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001172 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1173 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001174 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001175 // propagation master's thread values of threadprivate variables to local
1176 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001177 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1178 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1179 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001180 }
1181 CGF.EmitOMPPrivateClause(S, PrivateScope);
1182 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1183 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001184 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001185 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001187 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1188 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001189 emitPostUpdateForReductionClause(
1190 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001191}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001192
Alexey Bataev0f34da12015-07-02 04:17:07 +00001193void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1194 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001195 RunCleanupsScope BodyScope(*this);
1196 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001197 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001198 EmitIgnoredExpr(I);
1199 }
Alexander Musman3276a272015-03-21 10:12:56 +00001200 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001201 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001202 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001203 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001204 }
1205
Alexander Musmana5f070a2014-10-01 06:03:56 +00001206 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001207 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001208 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001209 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001210 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001211 // The end (updates/cleanups).
1212 EmitBlock(Continue.getBlock());
1213 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001214}
1215
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001216void CodeGenFunction::EmitOMPInnerLoop(
1217 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1218 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001219 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1220 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001221 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001222
1223 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001224 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001225 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001226 const SourceRange &R = S.getSourceRange();
1227 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1228 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001229
1230 // If there are any cleanups between here and the loop-exit scope,
1231 // create a block to stage a loop exit along.
1232 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001233 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001234 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001235
Alexander Musmand196ef22014-10-07 08:57:09 +00001236 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001237
Alexey Bataev2df54a02015-03-12 08:53:29 +00001238 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001239 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001240 if (ExitBlock != LoopExit.getBlock()) {
1241 EmitBlock(ExitBlock);
1242 EmitBranchThroughCleanup(LoopExit);
1243 }
1244
1245 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001246 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001247
1248 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001249 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001250 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1251
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001252 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001253
1254 // Emit "IV = IV + 1" and a back-edge to the condition block.
1255 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001256 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001257 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001258 BreakContinueStack.pop_back();
1259 EmitBranch(CondBlock);
1260 LoopStack.pop();
1261 // Emit the fall-through block.
1262 EmitBlock(LoopExit.getBlock());
1263}
1264
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001265bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001266 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001267 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001268 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001269 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001270 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001271 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001272 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001273 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001274 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1275 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1276 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1277 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1278 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1279 VD->getInit()->getType(), VK_LValue,
1280 VD->getInit()->getExprLoc());
1281 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1282 VD->getType()),
1283 /*capturedByInit=*/false);
1284 EmitAutoVarCleanups(Emission);
1285 } else
1286 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001287 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001288 // Emit the linear steps for the linear clauses.
1289 // If a step is not constant, it is pre-calculated before the loop.
1290 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1291 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001292 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001293 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001294 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001295 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001296 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001297 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001298}
1299
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001300void CodeGenFunction::EmitOMPLinearClauseFinal(
1301 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001302 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001303 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001304 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001305 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001306 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001307 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001308 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001309 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001310 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001311 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001312 // If the first post-update expression is found, emit conditional
1313 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001314 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1315 DoneBB = createBasicBlock(".omp.linear.pu.done");
1316 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1317 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001318 }
1319 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001320 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1321 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001322 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001323 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001324 Address OrigAddr = EmitLValue(&DRE).getAddress();
1325 CodeGenFunction::OMPPrivateScope VarScope(*this);
1326 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001327 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001329 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001330 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001331 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001332 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001333 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001334 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001335 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001336}
1337
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001338static void emitAlignedClause(CodeGenFunction &CGF,
1339 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001340 if (!CGF.HaveInsertPoint())
1341 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001342 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001343 unsigned ClauseAlignment = 0;
1344 if (auto AlignmentExpr = Clause->getAlignment()) {
1345 auto AlignmentCI =
1346 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1347 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001348 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001349 for (auto E : Clause->varlists()) {
1350 unsigned Alignment = ClauseAlignment;
1351 if (Alignment == 0) {
1352 // OpenMP [2.8.1, Description]
1353 // If no optional parameter is specified, implementation-defined default
1354 // alignments for SIMD instructions on the target platforms are assumed.
1355 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001356 CGF.getContext()
1357 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1358 E->getType()->getPointeeType()))
1359 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001360 }
1361 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1362 "alignment is not power of 2");
1363 if (Alignment != 0) {
1364 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1365 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1366 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001367 }
1368 }
1369}
1370
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001371void CodeGenFunction::EmitOMPPrivateLoopCounters(
1372 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1373 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001374 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001375 auto I = S.private_counters().begin();
1376 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001377 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1378 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001379 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001380 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001381 if (!LocalDeclMap.count(PrivateVD)) {
1382 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1383 EmitAutoVarCleanups(VarEmission);
1384 }
1385 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1386 /*RefersToEnclosingVariableOrCapture=*/false,
1387 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1388 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001389 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001390 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1391 VD->hasGlobalStorage()) {
1392 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1393 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1394 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1395 E->getType(), VK_LValue, E->getExprLoc());
1396 return EmitLValue(&DRE).getAddress();
1397 });
1398 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001399 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001400 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001401}
1402
Alexey Bataev62dbb972015-04-22 11:59:37 +00001403static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1404 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1405 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001406 if (!CGF.HaveInsertPoint())
1407 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001408 {
1409 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001411 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001412 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001413 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001414 CGF.EmitIgnoredExpr(I);
1415 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001416 }
1417 // Check that loop is executed at least one time.
1418 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1419}
1420
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001421void CodeGenFunction::EmitOMPLinearClause(
1422 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1423 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001424 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001425 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1426 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1427 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1428 for (auto *C : LoopDirective->counters()) {
1429 SIMDLCVs.insert(
1430 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1431 }
1432 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001433 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001434 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001435 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001436 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1437 auto *PrivateVD =
1438 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001439 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1440 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1441 // Emit private VarDecl with copy init.
1442 EmitVarDecl(*PrivateVD);
1443 return GetAddrOfLocalVar(PrivateVD);
1444 });
1445 assert(IsRegistered && "linear var already registered as private");
1446 // Silence the warning about unused variable.
1447 (void)IsRegistered;
1448 } else
1449 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001450 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001451 }
1452 }
1453}
1454
Alexey Bataev45bfad52015-08-21 12:19:04 +00001455static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001456 const OMPExecutableDirective &D,
1457 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001458 if (!CGF.HaveInsertPoint())
1459 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001460 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001461 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1462 /*ignoreResult=*/true);
1463 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1464 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1465 // In presence of finite 'safelen', it may be unsafe to mark all
1466 // the memory instructions parallel, because loop-carried
1467 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001468 if (!IsMonotonic)
1469 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001470 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001471 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1472 /*ignoreResult=*/true);
1473 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001474 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001475 // In presence of finite 'safelen', it may be unsafe to mark all
1476 // the memory instructions parallel, because loop-carried
1477 // dependences of 'safelen' iterations are possible.
1478 CGF.LoopStack.setParallel(false);
1479 }
1480}
1481
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001482void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1483 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001484 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001485 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001486 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001487 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001488}
1489
Alexey Bataevef549a82016-03-09 09:49:09 +00001490void CodeGenFunction::EmitOMPSimdFinal(
1491 const OMPLoopDirective &D,
1492 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001493 if (!HaveInsertPoint())
1494 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001495 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001496 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001497 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001498 for (auto F : D.finals()) {
1499 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001500 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1501 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1502 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1503 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001504 if (!DoneBB) {
1505 if (auto *Cond = CondGen(*this)) {
1506 // If the first post-update expression is found, emit conditional
1507 // block if it was requested.
1508 auto *ThenBB = createBasicBlock(".omp.final.then");
1509 DoneBB = createBasicBlock(".omp.final.done");
1510 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1511 EmitBlock(ThenBB);
1512 }
1513 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001514 Address OrigAddr = Address::invalid();
1515 if (CED)
1516 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1517 else {
1518 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1519 /*RefersToEnclosingVariableOrCapture=*/false,
1520 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1521 OrigAddr = EmitLValue(&DRE).getAddress();
1522 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001523 OMPPrivateScope VarScope(*this);
1524 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001525 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001526 (void)VarScope.Privatize();
1527 EmitIgnoredExpr(F);
1528 }
1529 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001530 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001531 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001532 if (DoneBB)
1533 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001534}
1535
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001536static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1537 const OMPLoopDirective &S,
1538 CodeGenFunction::JumpDest LoopExit) {
1539 CGF.EmitOMPLoopBody(S, LoopExit);
1540 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001541}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001542
Alexey Bataevf8365372017-11-17 17:57:25 +00001543static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1544 PrePostActionTy &Action) {
1545 Action.Enter(CGF);
1546 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1547 "Expected simd directive");
1548 OMPLoopScope PreInitScope(CGF, S);
1549 // if (PreCond) {
1550 // for (IV in 0..LastIteration) BODY;
1551 // <Final counter/linear vars updates>;
1552 // }
1553 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001554
Alexey Bataevf8365372017-11-17 17:57:25 +00001555 // Emit: if (PreCond) - begin.
1556 // If the condition constant folds and can be elided, avoid emitting the
1557 // whole loop.
1558 bool CondConstant;
1559 llvm::BasicBlock *ContBlock = nullptr;
1560 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1561 if (!CondConstant)
1562 return;
1563 } else {
1564 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1565 ContBlock = CGF.createBasicBlock("simd.if.end");
1566 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1567 CGF.getProfileCount(&S));
1568 CGF.EmitBlock(ThenBlock);
1569 CGF.incrementProfileCounter(&S);
1570 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001571
Alexey Bataevf8365372017-11-17 17:57:25 +00001572 // Emit the loop iteration variable.
1573 const Expr *IVExpr = S.getIterationVariable();
1574 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1575 CGF.EmitVarDecl(*IVDecl);
1576 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001577
Alexey Bataevf8365372017-11-17 17:57:25 +00001578 // Emit the iterations count variable.
1579 // If it is not a variable, Sema decided to calculate iterations count on
1580 // each iteration (e.g., it is foldable into a constant).
1581 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1582 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1583 // Emit calculation of the iterations count.
1584 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1585 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001586
Alexey Bataevf8365372017-11-17 17:57:25 +00001587 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001588
Alexey Bataevf8365372017-11-17 17:57:25 +00001589 emitAlignedClause(CGF, S);
1590 (void)CGF.EmitOMPLinearClauseInit(S);
1591 {
1592 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1593 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1594 CGF.EmitOMPLinearClause(S, LoopScope);
1595 CGF.EmitOMPPrivateClause(S, LoopScope);
1596 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1597 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1598 (void)LoopScope.Privatize();
1599 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1600 S.getInc(),
1601 [&S](CodeGenFunction &CGF) {
1602 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1603 CGF.EmitStopPoint(&S);
1604 },
1605 [](CodeGenFunction &) {});
1606 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001607 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001608 // Emit final copy of the lastprivate variables at the end of loops.
1609 if (HasLastprivateClause)
1610 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1611 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1612 emitPostUpdateForReductionClause(
1613 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1614 }
1615 CGF.EmitOMPLinearClauseFinal(
1616 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1617 // Emit: if (PreCond) - end.
1618 if (ContBlock) {
1619 CGF.EmitBranch(ContBlock);
1620 CGF.EmitBlock(ContBlock, true);
1621 }
1622}
1623
1624void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1626 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001627 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001628 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001629 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001630}
1631
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001632void CodeGenFunction::EmitOMPOuterLoop(
1633 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1634 CodeGenFunction::OMPPrivateScope &LoopScope,
1635 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1636 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1637 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001638 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001639
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001640 const Expr *IVExpr = S.getIterationVariable();
1641 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1642 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1643
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001644 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1645
1646 // Start the loop with a block that tests the condition.
1647 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1648 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001649 const SourceRange &R = S.getSourceRange();
1650 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1651 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001652
1653 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001654 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001655 // UB = min(UB, GlobalUB) or
1656 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1657 // 'distribute parallel for')
1658 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001659 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001660 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001661 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001662 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001663 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001664 BoolCondVal =
1665 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1666 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001667 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001668
1669 // If there are any cleanups between here and the loop-exit scope,
1670 // create a block to stage a loop exit along.
1671 auto ExitBlock = LoopExit.getBlock();
1672 if (LoopScope.requiresCleanups())
1673 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1674
1675 auto LoopBody = createBasicBlock("omp.dispatch.body");
1676 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1677 if (ExitBlock != LoopExit.getBlock()) {
1678 EmitBlock(ExitBlock);
1679 EmitBranchThroughCleanup(LoopExit);
1680 }
1681 EmitBlock(LoopBody);
1682
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1684 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001685 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001686 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001687
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001688 // Create a block for the increment.
1689 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1690 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1691
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001692 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1693 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001694 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1695 LoopStack.setParallel(!IsMonotonic);
1696 else
1697 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001698
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001699 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001700
1701 // when 'distribute' is not combined with a 'for':
1702 // while (idx <= UB) { BODY; ++idx; }
1703 // when 'distribute' is combined with a 'for'
1704 // (e.g. 'distribute parallel for')
1705 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1706 EmitOMPInnerLoop(
1707 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1708 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1709 CodeGenLoop(CGF, S, LoopExit);
1710 },
1711 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1712 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1713 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001714
1715 EmitBlock(Continue.getBlock());
1716 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001717 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001718 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001719 EmitIgnoredExpr(LoopArgs.NextLB);
1720 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001721 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001722
1723 EmitBranch(CondBlock);
1724 LoopStack.pop();
1725 // Emit the fall-through block.
1726 EmitBlock(LoopExit.getBlock());
1727
1728 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001729 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1730 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001731 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1732 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001733 };
1734 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001735}
1736
1737void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001738 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001739 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001740 const OMPLoopArguments &LoopArgs,
1741 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001742 auto &RT = CGM.getOpenMPRuntime();
1743
1744 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001745 const bool DynamicOrOrdered =
1746 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001747
1748 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001749 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001750 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001751 "static non-chunked schedule does not need outer loop");
1752
1753 // Emit outer loop.
1754 //
1755 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1756 // When schedule(dynamic,chunk_size) is specified, the iterations are
1757 // distributed to threads in the team in chunks as the threads request them.
1758 // Each thread executes a chunk of iterations, then requests another chunk,
1759 // until no chunks remain to be distributed. Each chunk contains chunk_size
1760 // iterations, except for the last chunk to be distributed, which may have
1761 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1762 //
1763 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1764 // to threads in the team in chunks as the executing threads request them.
1765 // Each thread executes a chunk of iterations, then requests another chunk,
1766 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1767 // each chunk is proportional to the number of unassigned iterations divided
1768 // by the number of threads in the team, decreasing to 1. For a chunk_size
1769 // with value k (greater than 1), the size of each chunk is determined in the
1770 // same way, with the restriction that the chunks do not contain fewer than k
1771 // iterations (except for the last chunk to be assigned, which may have fewer
1772 // than k iterations).
1773 //
1774 // When schedule(auto) is specified, the decision regarding scheduling is
1775 // delegated to the compiler and/or runtime system. The programmer gives the
1776 // implementation the freedom to choose any possible mapping of iterations to
1777 // threads in the team.
1778 //
1779 // When schedule(runtime) is specified, the decision regarding scheduling is
1780 // deferred until run time, and the schedule and chunk size are taken from the
1781 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1782 // implementation defined
1783 //
1784 // while(__kmpc_dispatch_next(&LB, &UB)) {
1785 // idx = LB;
1786 // while (idx <= UB) { BODY; ++idx;
1787 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1788 // } // inner loop
1789 // }
1790 //
1791 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1792 // When schedule(static, chunk_size) is specified, iterations are divided into
1793 // chunks of size chunk_size, and the chunks are assigned to the threads in
1794 // the team in a round-robin fashion in the order of the thread number.
1795 //
1796 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1797 // while (idx <= UB) { BODY; ++idx; } // inner loop
1798 // LB = LB + ST;
1799 // UB = UB + ST;
1800 // }
1801 //
1802
1803 const Expr *IVExpr = S.getIterationVariable();
1804 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1805 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1806
1807 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001808 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1809 llvm::Value *LBVal = DispatchBounds.first;
1810 llvm::Value *UBVal = DispatchBounds.second;
1811 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1812 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001813 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001814 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001815 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001816 CGOpenMPRuntime::StaticRTInput StaticInit(
1817 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1818 LoopArgs.ST, LoopArgs.Chunk);
1819 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1820 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001821 }
1822
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001823 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1824 const unsigned IVSize,
1825 const bool IVSigned) {
1826 if (Ordered) {
1827 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1828 IVSigned);
1829 }
1830 };
1831
1832 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1833 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1834 OuterLoopArgs.IncExpr = S.getInc();
1835 OuterLoopArgs.Init = S.getInit();
1836 OuterLoopArgs.Cond = S.getCond();
1837 OuterLoopArgs.NextLB = S.getNextLowerBound();
1838 OuterLoopArgs.NextUB = S.getNextUpperBound();
1839 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1840 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001841}
1842
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001843static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1844 const unsigned IVSize, const bool IVSigned) {}
1845
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001846void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001847 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1848 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1849 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001850
1851 auto &RT = CGM.getOpenMPRuntime();
1852
1853 // Emit outer loop.
1854 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1855 // dynamic
1856 //
1857
1858 const Expr *IVExpr = S.getIterationVariable();
1859 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1860 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1861
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001862 CGOpenMPRuntime::StaticRTInput StaticInit(
1863 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1864 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1865 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001866
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001867 // for combined 'distribute' and 'for' the increment expression of distribute
1868 // is store in DistInc. For 'distribute' alone, it is in Inc.
1869 Expr *IncExpr;
1870 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1871 IncExpr = S.getDistInc();
1872 else
1873 IncExpr = S.getInc();
1874
1875 // this routine is shared by 'omp distribute parallel for' and
1876 // 'omp distribute': select the right EUB expression depending on the
1877 // directive
1878 OMPLoopArguments OuterLoopArgs;
1879 OuterLoopArgs.LB = LoopArgs.LB;
1880 OuterLoopArgs.UB = LoopArgs.UB;
1881 OuterLoopArgs.ST = LoopArgs.ST;
1882 OuterLoopArgs.IL = LoopArgs.IL;
1883 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1884 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1885 ? S.getCombinedEnsureUpperBound()
1886 : S.getEnsureUpperBound();
1887 OuterLoopArgs.IncExpr = IncExpr;
1888 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1889 ? S.getCombinedInit()
1890 : S.getInit();
1891 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1892 ? S.getCombinedCond()
1893 : S.getCond();
1894 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1895 ? S.getCombinedNextLowerBound()
1896 : S.getNextLowerBound();
1897 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1898 ? S.getCombinedNextUpperBound()
1899 : S.getNextUpperBound();
1900
1901 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1902 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1903 emitEmptyOrdered);
1904}
1905
1906/// Emit a helper variable and return corresponding lvalue.
1907static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1908 const DeclRefExpr *Helper) {
1909 auto VDecl = cast<VarDecl>(Helper->getDecl());
1910 CGF.EmitVarDecl(*VDecl);
1911 return CGF.EmitLValue(Helper);
1912}
1913
1914static std::pair<LValue, LValue>
1915emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1916 const OMPExecutableDirective &S) {
1917 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1918 LValue LB =
1919 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1920 LValue UB =
1921 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1922
1923 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1924 // parallel for') we need to use the 'distribute'
1925 // chunk lower and upper bounds rather than the whole loop iteration
1926 // space. These are parameters to the outlined function for 'parallel'
1927 // and we copy the bounds of the previous schedule into the
1928 // the current ones.
1929 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1930 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1931 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1932 PrevLBVal = CGF.EmitScalarConversion(
1933 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1934 LS.getIterationVariable()->getType(), SourceLocation());
1935 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1936 PrevUBVal = CGF.EmitScalarConversion(
1937 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1938 LS.getIterationVariable()->getType(), SourceLocation());
1939
1940 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1941 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1942
1943 return {LB, UB};
1944}
1945
1946/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1947/// we need to use the LB and UB expressions generated by the worksharing
1948/// code generation support, whereas in non combined situations we would
1949/// just emit 0 and the LastIteration expression
1950/// This function is necessary due to the difference of the LB and UB
1951/// types for the RT emission routines for 'for_static_init' and
1952/// 'for_dispatch_init'
1953static std::pair<llvm::Value *, llvm::Value *>
1954emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1955 const OMPExecutableDirective &S,
1956 Address LB, Address UB) {
1957 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1958 const Expr *IVExpr = LS.getIterationVariable();
1959 // when implementing a dynamic schedule for a 'for' combined with a
1960 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1961 // is not normalized as each team only executes its own assigned
1962 // distribute chunk
1963 QualType IteratorTy = IVExpr->getType();
1964 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1965 SourceLocation());
1966 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1967 SourceLocation());
1968 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001969}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001970
1971static void emitDistributeParallelForDistributeInnerBoundParams(
1972 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1973 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1974 const auto &Dir = cast<OMPLoopDirective>(S);
1975 LValue LB =
1976 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1977 auto LBCast = CGF.Builder.CreateIntCast(
1978 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1979 CapturedVars.push_back(LBCast);
1980 LValue UB =
1981 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1982
1983 auto UBCast = CGF.Builder.CreateIntCast(
1984 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1985 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001986}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001987
1988static void
1989emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1990 const OMPLoopDirective &S,
1991 CodeGenFunction::JumpDest LoopExit) {
1992 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1993 PrePostActionTy &) {
1994 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1995 emitDistributeParallelForInnerBounds,
1996 emitDistributeParallelForDispatchBounds);
1997 };
1998
1999 emitCommonOMPParallelDirective(
2000 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
2001 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002002}
2003
Carlo Bertolli9925f152016-06-27 14:55:37 +00002004void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2005 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002006 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2007 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2008 S.getDistInc());
2009 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002010 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002011 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
2012 /*HasCancel=*/false);
2013 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2014 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002015}
2016
Kelvin Li4a39add2016-07-05 05:00:15 +00002017void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2018 const OMPDistributeParallelForSimdDirective &S) {
2019 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2020 CGM.getOpenMPRuntime().emitInlinedDirective(
2021 *this, OMPD_distribute_parallel_for_simd,
2022 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2023 OMPLoopScope PreInitScope(CGF, S);
2024 CGF.EmitStmt(
2025 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2026 });
2027}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002028
2029void CodeGenFunction::EmitOMPDistributeSimdDirective(
2030 const OMPDistributeSimdDirective &S) {
2031 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2032 CGM.getOpenMPRuntime().emitInlinedDirective(
2033 *this, OMPD_distribute_simd,
2034 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2035 OMPLoopScope PreInitScope(CGF, S);
2036 CGF.EmitStmt(
2037 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2038 });
2039}
2040
Alexey Bataevf8365372017-11-17 17:57:25 +00002041void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2042 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2043 // Emit SPMD target parallel for region as a standalone region.
2044 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2045 emitOMPSimdRegion(CGF, S, Action);
2046 };
2047 llvm::Function *Fn;
2048 llvm::Constant *Addr;
2049 // Emit target region as a standalone region.
2050 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2051 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2052 assert(Fn && Addr && "Target device function emission failed.");
2053}
2054
Kelvin Li986330c2016-07-20 22:57:10 +00002055void CodeGenFunction::EmitOMPTargetSimdDirective(
2056 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002057 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2058 emitOMPSimdRegion(CGF, S, Action);
2059 };
2060 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002061}
2062
Kelvin Li4e325f72016-10-25 12:50:55 +00002063void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2064 const OMPTeamsDistributeSimdDirective &S) {
2065 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2066 CGM.getOpenMPRuntime().emitInlinedDirective(
2067 *this, OMPD_teams_distribute_simd,
2068 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2069 OMPLoopScope PreInitScope(CGF, S);
2070 CGF.EmitStmt(
2071 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2072 });
2073}
2074
Kelvin Li579e41c2016-11-30 23:51:03 +00002075void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2076 const OMPTeamsDistributeParallelForSimdDirective &S) {
2077 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2078 CGM.getOpenMPRuntime().emitInlinedDirective(
2079 *this, OMPD_teams_distribute_parallel_for_simd,
2080 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2081 OMPLoopScope PreInitScope(CGF, S);
2082 CGF.EmitStmt(
2083 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2084 });
2085}
Kelvin Li4e325f72016-10-25 12:50:55 +00002086
Kelvin Li7ade93f2016-12-09 03:24:30 +00002087void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2088 const OMPTeamsDistributeParallelForDirective &S) {
2089 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2090 CGM.getOpenMPRuntime().emitInlinedDirective(
2091 *this, OMPD_teams_distribute_parallel_for,
2092 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2093 OMPLoopScope PreInitScope(CGF, S);
2094 CGF.EmitStmt(
2095 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2096 });
2097}
2098
Kelvin Li83c451e2016-12-25 04:52:54 +00002099void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2100 const OMPTargetTeamsDistributeDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002101 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li26fd21a2016-12-28 17:57:07 +00002102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002105 CGF.EmitStmt(
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002107 });
2108}
2109
Kelvin Li80e8f562016-12-29 22:16:30 +00002110void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2111 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002112 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002113 CGM.getOpenMPRuntime().emitInlinedDirective(
2114 *this, OMPD_target_teams_distribute_parallel_for,
2115 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2116 CGF.EmitStmt(
2117 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2118 });
2119}
2120
Kelvin Li1851df52017-01-03 05:23:48 +00002121void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2122 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002123 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002124 CGM.getOpenMPRuntime().emitInlinedDirective(
2125 *this, OMPD_target_teams_distribute_parallel_for_simd,
2126 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2127 CGF.EmitStmt(
2128 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2129 });
2130}
2131
Kelvin Lida681182017-01-10 18:08:18 +00002132void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2133 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002134 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002135 CGM.getOpenMPRuntime().emitInlinedDirective(
2136 *this, OMPD_target_teams_distribute_simd,
2137 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2138 CGF.EmitStmt(
2139 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2140 });
2141}
2142
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002143namespace {
2144 struct ScheduleKindModifiersTy {
2145 OpenMPScheduleClauseKind Kind;
2146 OpenMPScheduleClauseModifier M1;
2147 OpenMPScheduleClauseModifier M2;
2148 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2149 OpenMPScheduleClauseModifier M1,
2150 OpenMPScheduleClauseModifier M2)
2151 : Kind(Kind), M1(M1), M2(M2) {}
2152 };
2153} // namespace
2154
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002155bool CodeGenFunction::EmitOMPWorksharingLoop(
2156 const OMPLoopDirective &S, Expr *EUB,
2157 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2158 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002159 // Emit the loop iteration variable.
2160 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2161 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2162 EmitVarDecl(*IVDecl);
2163
2164 // Emit the iterations count variable.
2165 // If it is not a variable, Sema decided to calculate iterations count on each
2166 // iteration (e.g., it is foldable into a constant).
2167 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2168 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2169 // Emit calculation of the iterations count.
2170 EmitIgnoredExpr(S.getCalcLastIteration());
2171 }
2172
2173 auto &RT = CGM.getOpenMPRuntime();
2174
Alexey Bataev38e89532015-04-16 04:54:05 +00002175 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002176 // Check pre-condition.
2177 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002178 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002179 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002180 // If the condition constant folds and can be elided, avoid emitting the
2181 // whole loop.
2182 bool CondConstant;
2183 llvm::BasicBlock *ContBlock = nullptr;
2184 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2185 if (!CondConstant)
2186 return false;
2187 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002188 auto *ThenBlock = createBasicBlock("omp.precond.then");
2189 ContBlock = createBasicBlock("omp.precond.end");
2190 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002191 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002192 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002193 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002194 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002195
Alexey Bataev8b427062016-05-25 12:36:08 +00002196 bool Ordered = false;
2197 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2198 if (OrderedClause->getNumForLoops())
2199 RT.emitDoacrossInit(*this, S);
2200 else
2201 Ordered = true;
2202 }
2203
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002204 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002205 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002206 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002207 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002208
2209 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2210 LValue LB = Bounds.first;
2211 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002212 LValue ST =
2213 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2214 LValue IL =
2215 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2216
Alexander Musmanc6388682014-12-15 07:07:06 +00002217 // Emit 'then' code.
2218 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002219 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002220 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002221 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002222 // initialization of firstprivate variables and post-update of
2223 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002224 CGM.getOpenMPRuntime().emitBarrierCall(
2225 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2226 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002227 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002228 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002229 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002230 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002231 EmitOMPPrivateLoopCounters(S, LoopScope);
2232 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002233 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002234
2235 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002236 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002237 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002238 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002239 ScheduleKind.Schedule = C->getScheduleKind();
2240 ScheduleKind.M1 = C->getFirstScheduleModifier();
2241 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002242 if (const auto *Ch = C->getChunkSize()) {
2243 Chunk = EmitScalarExpr(Ch);
2244 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2245 S.getIterationVariable()->getType(),
2246 S.getLocStart());
2247 }
2248 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002249 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2250 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002251 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2252 // If the static schedule kind is specified or if the ordered clause is
2253 // specified, and if no monotonic modifier is specified, the effect will
2254 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002255 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002256 /* Chunked */ Chunk != nullptr) &&
2257 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002258 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2259 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002260 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2261 // When no chunk_size is specified, the iteration space is divided into
2262 // chunks that are approximately equal in size, and at most one chunk is
2263 // distributed to each thread. Note that the size of the chunks is
2264 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002265 CGOpenMPRuntime::StaticRTInput StaticInit(
2266 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2267 UB.getAddress(), ST.getAddress());
2268 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2269 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002270 auto LoopExit =
2271 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002272 // UB = min(UB, GlobalUB);
2273 EmitIgnoredExpr(S.getEnsureUpperBound());
2274 // IV = LB;
2275 EmitIgnoredExpr(S.getInit());
2276 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002277 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2278 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002279 [&S, LoopExit](CodeGenFunction &CGF) {
2280 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002281 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002282 },
2283 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002284 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002285 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002286 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002287 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2288 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002289 };
2290 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002291 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002292 const bool IsMonotonic =
2293 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2294 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2295 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2296 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002297 // Emit the outer loop, which requests its work chunk [LB..UB] from
2298 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002299 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2300 ST.getAddress(), IL.getAddress(),
2301 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002302 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002303 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002304 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002305 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2306 EmitOMPSimdFinal(S,
2307 [&](CodeGenFunction &CGF) -> llvm::Value * {
2308 return CGF.Builder.CreateIsNotNull(
2309 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2310 });
2311 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002312 EmitOMPReductionClauseFinal(
2313 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2314 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2315 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002316 // Emit post-update of the reduction variables if IsLastIter != 0.
2317 emitPostUpdateForReductionClause(
2318 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2319 return CGF.Builder.CreateIsNotNull(
2320 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2321 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002322 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2323 if (HasLastprivateClause)
2324 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002325 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2326 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002327 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002328 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002329 return CGF.Builder.CreateIsNotNull(
2330 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2331 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002332 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002333 if (ContBlock) {
2334 EmitBranch(ContBlock);
2335 EmitBlock(ContBlock, true);
2336 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002337 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002338 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002339}
2340
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002341/// The following two functions generate expressions for the loop lower
2342/// and upper bounds in case of static and dynamic (dispatch) schedule
2343/// of the associated 'for' or 'distribute' loop.
2344static std::pair<LValue, LValue>
2345emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2346 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2347 LValue LB =
2348 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2349 LValue UB =
2350 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2351 return {LB, UB};
2352}
2353
2354/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2355/// consider the lower and upper bound expressions generated by the
2356/// worksharing loop support, but we use 0 and the iteration space size as
2357/// constants
2358static std::pair<llvm::Value *, llvm::Value *>
2359emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2360 Address LB, Address UB) {
2361 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2362 const Expr *IVExpr = LS.getIterationVariable();
2363 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2364 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2365 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2366 return {LBVal, UBVal};
2367}
2368
Alexander Musmanc6388682014-12-15 07:07:06 +00002369void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002370 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002371 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2372 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002373 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002374 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2375 emitForLoopBounds,
2376 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002377 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002378 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002379 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002380 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2381 S.hasCancel());
2382 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002383
2384 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002385 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002386 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2387 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002388}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002389
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002390void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002391 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002392 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2393 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002394 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2395 emitForLoopBounds,
2396 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002397 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002398 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002399 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002400 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2401 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002402
2403 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002404 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002405 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2406 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002407}
2408
Alexey Bataev2df54a02015-03-12 08:53:29 +00002409static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2410 const Twine &Name,
2411 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002412 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002413 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002414 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002415 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002416}
2417
Alexey Bataev3392d762016-02-16 11:18:12 +00002418void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002419 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2420 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002421 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002422 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2423 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002424 auto &C = CGF.CGM.getContext();
2425 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2426 // Emit helper vars inits.
2427 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2428 CGF.Builder.getInt32(0));
2429 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2430 : CGF.Builder.getInt32(0);
2431 LValue UB =
2432 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2433 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2434 CGF.Builder.getInt32(1));
2435 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2436 CGF.Builder.getInt32(0));
2437 // Loop counter.
2438 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2439 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2440 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2441 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2442 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2443 // Generate condition for loop.
2444 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002445 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002446 // Increment for loop counter.
2447 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2448 S.getLocStart());
2449 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2450 // Iterate through all sections and emit a switch construct:
2451 // switch (IV) {
2452 // case 0:
2453 // <SectionStmt[0]>;
2454 // break;
2455 // ...
2456 // case <NumSection> - 1:
2457 // <SectionStmt[<NumSection> - 1]>;
2458 // break;
2459 // }
2460 // .omp.sections.exit:
2461 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2462 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2463 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2464 CS == nullptr ? 1 : CS->size());
2465 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002466 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002467 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002468 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2469 CGF.EmitBlock(CaseBB);
2470 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002471 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002472 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002473 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002474 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002475 } else {
2476 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2477 CGF.EmitBlock(CaseBB);
2478 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2479 CGF.EmitStmt(Stmt);
2480 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002481 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002482 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002483 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002484
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2486 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002487 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002488 // initialization of firstprivate variables and post-update of lastprivate
2489 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002490 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2491 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2492 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002493 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002494 CGF.EmitOMPPrivateClause(S, LoopScope);
2495 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2496 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2497 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002498
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002499 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002500 OpenMPScheduleTy ScheduleKind;
2501 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002502 CGOpenMPRuntime::StaticRTInput StaticInit(
2503 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2504 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002505 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002506 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002507 // UB = min(UB, GlobalUB);
2508 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2509 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2510 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2511 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2512 // IV = LB;
2513 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2514 // while (idx <= UB) { BODY; ++idx; }
2515 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2516 [](CodeGenFunction &) {});
2517 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002518 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002519 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2520 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002521 };
2522 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002523 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002524 // Emit post-update of the reduction variables if IsLastIter != 0.
2525 emitPostUpdateForReductionClause(
2526 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2527 return CGF.Builder.CreateIsNotNull(
2528 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2529 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002530
2531 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2532 if (HasLastprivates)
2533 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002534 S, /*NoFinals=*/false,
2535 CGF.Builder.CreateIsNotNull(
2536 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002537 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002538
2539 bool HasCancel = false;
2540 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2541 HasCancel = OSD->hasCancel();
2542 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2543 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002544 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002545 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2546 HasCancel);
2547 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2548 // clause. Otherwise the barrier will be generated by the codegen for the
2549 // directive.
2550 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002551 // Emit implicit barrier to synchronize threads and avoid data races on
2552 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002553 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2554 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002555 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002556}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002557
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002558void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002559 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002560 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002561 EmitSections(S);
2562 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002563 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002564 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002565 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2566 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002567 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002568}
2569
2570void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002571 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002572 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002573 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002574 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002575 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2576 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002577}
2578
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002579void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002580 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002581 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002582 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002583 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002584 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002585 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002586 // Build a list of copyprivate variables along with helper expressions
2587 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002588 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002589 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002590 DestExprs.append(C->destination_exprs().begin(),
2591 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002592 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002593 AssignmentOps.append(C->assignment_ops().begin(),
2594 C->assignment_ops().end());
2595 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002596 // Emit code for 'single' region along with 'copyprivate' clauses
2597 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2598 Action.Enter(CGF);
2599 OMPPrivateScope SingleScope(CGF);
2600 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2601 CGF.EmitOMPPrivateClause(S, SingleScope);
2602 (void)SingleScope.Privatize();
2603 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2604 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002605 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002606 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002607 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2608 CopyprivateVars, DestExprs,
2609 SrcExprs, AssignmentOps);
2610 }
2611 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2612 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002613 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002614 CGM.getOpenMPRuntime().emitBarrierCall(
2615 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002616 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002617 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002618}
2619
Alexey Bataev8d690652014-12-04 07:23:53 +00002620void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002621 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2622 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002623 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002624 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002625 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002626 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002627}
2628
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002629void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002630 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2631 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002632 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002633 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002634 Expr *Hint = nullptr;
2635 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2636 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002637 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002638 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2639 S.getDirectiveName().getAsString(),
2640 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002641}
2642
Alexey Bataev671605e2015-04-13 05:28:11 +00002643void CodeGenFunction::EmitOMPParallelForDirective(
2644 const OMPParallelForDirective &S) {
2645 // Emit directive as a combined directive that consists of two implicit
2646 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002647 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002648 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002649 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2650 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002651 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002652 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2653 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002654}
2655
Alexander Musmane4e893b2014-09-23 09:33:00 +00002656void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002657 const OMPParallelForSimdDirective &S) {
2658 // Emit directive as a combined directive that consists of two implicit
2659 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002660 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002661 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2662 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002663 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002664 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2665 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002666}
2667
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002668void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002669 const OMPParallelSectionsDirective &S) {
2670 // Emit directive as a combined directive that consists of two implicit
2671 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002672 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2673 CGF.EmitSections(S);
2674 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002675 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2676 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002677}
2678
Alexey Bataev7292c292016-04-25 12:22:29 +00002679void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2680 const RegionCodeGenTy &BodyGen,
2681 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002682 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002683 // Emit outlined function for task construct.
2684 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002685 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002686 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002687 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002688 // Check if the task is final
2689 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2690 // If the condition constant folds and can be elided, try to avoid emitting
2691 // the condition and the dead arm of the if/else.
2692 auto *Cond = Clause->getCondition();
2693 bool CondConstant;
2694 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2695 Data.Final.setInt(CondConstant);
2696 else
2697 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2698 } else {
2699 // By default the task is not final.
2700 Data.Final.setInt(/*IntVal=*/false);
2701 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002702 // Check if the task has 'priority' clause.
2703 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002704 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002705 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002706 Data.Priority.setPointer(EmitScalarConversion(
2707 EmitScalarExpr(Prio), Prio->getType(),
2708 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2709 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002710 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002711 // The first function argument for tasks is a thread id, the second one is a
2712 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002713 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2714 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002715 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002716 auto IRef = C->varlist_begin();
2717 for (auto *IInit : C->private_copies()) {
2718 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2719 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002720 Data.PrivateVars.push_back(*IRef);
2721 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002722 }
2723 ++IRef;
2724 }
2725 }
2726 EmittedAsPrivate.clear();
2727 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002728 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002729 auto IRef = C->varlist_begin();
2730 auto IElemInitRef = C->inits().begin();
2731 for (auto *IInit : C->private_copies()) {
2732 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2733 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002734 Data.FirstprivateVars.push_back(*IRef);
2735 Data.FirstprivateCopies.push_back(IInit);
2736 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002737 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002738 ++IRef;
2739 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002740 }
2741 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002742 // Get list of lastprivate variables (for taskloops).
2743 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2744 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2745 auto IRef = C->varlist_begin();
2746 auto ID = C->destination_exprs().begin();
2747 for (auto *IInit : C->private_copies()) {
2748 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2749 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2750 Data.LastprivateVars.push_back(*IRef);
2751 Data.LastprivateCopies.push_back(IInit);
2752 }
2753 LastprivateDstsOrigs.insert(
2754 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2755 cast<DeclRefExpr>(*IRef)});
2756 ++IRef;
2757 ++ID;
2758 }
2759 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002760 SmallVector<const Expr *, 4> LHSs;
2761 SmallVector<const Expr *, 4> RHSs;
2762 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2763 auto IPriv = C->privates().begin();
2764 auto IRed = C->reduction_ops().begin();
2765 auto ILHS = C->lhs_exprs().begin();
2766 auto IRHS = C->rhs_exprs().begin();
2767 for (const auto *Ref : C->varlists()) {
2768 Data.ReductionVars.emplace_back(Ref);
2769 Data.ReductionCopies.emplace_back(*IPriv);
2770 Data.ReductionOps.emplace_back(*IRed);
2771 LHSs.emplace_back(*ILHS);
2772 RHSs.emplace_back(*IRHS);
2773 std::advance(IPriv, 1);
2774 std::advance(IRed, 1);
2775 std::advance(ILHS, 1);
2776 std::advance(IRHS, 1);
2777 }
2778 }
2779 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2780 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002781 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002782 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2783 for (auto *IRef : C->varlists())
2784 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002785 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002786 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002787 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002788 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002789 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2790 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002791 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002792 auto *CopyFn = CGF.Builder.CreateLoad(
2793 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2794 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2795 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2796 // Map privates.
2797 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2798 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2799 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002800 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002801 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2802 Address PrivatePtr = CGF.CreateMemTemp(
2803 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2804 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2805 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002806 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002807 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002808 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2809 Address PrivatePtr =
2810 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2811 ".firstpriv.ptr.addr");
2812 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2813 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002814 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002815 for (auto *E : Data.LastprivateVars) {
2816 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2817 Address PrivatePtr =
2818 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2819 ".lastpriv.ptr.addr");
2820 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2821 CallArgs.push_back(PrivatePtr.getPointer());
2822 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002823 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2824 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002825 for (auto &&Pair : LastprivateDstsOrigs) {
2826 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2827 DeclRefExpr DRE(
2828 const_cast<VarDecl *>(OrigVD),
2829 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2830 OrigVD) != nullptr,
2831 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2832 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2833 return CGF.EmitLValue(&DRE).getAddress();
2834 });
2835 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002836 for (auto &&Pair : PrivatePtrs) {
2837 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2838 CGF.getContext().getDeclAlign(Pair.first));
2839 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2840 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002841 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002842 if (Data.Reductions) {
2843 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2844 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2845 Data.ReductionOps);
2846 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2847 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2848 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2849 RedCG.emitSharedLValue(CGF, Cnt);
2850 RedCG.emitAggregateType(CGF, Cnt);
2851 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2852 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2853 Replacement =
2854 Address(CGF.EmitScalarConversion(
2855 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2856 CGF.getContext().getPointerType(
2857 Data.ReductionCopies[Cnt]->getType()),
2858 SourceLocation()),
2859 Replacement.getAlignment());
2860 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2861 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2862 [Replacement]() { return Replacement; });
2863 // FIXME: This must removed once the runtime library is fixed.
2864 // Emit required threadprivate variables for
2865 // initilizer/combiner/finalizer.
2866 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2867 RedCG, Cnt);
2868 }
2869 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002870 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002871 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002872 SmallVector<const Expr *, 4> InRedVars;
2873 SmallVector<const Expr *, 4> InRedPrivs;
2874 SmallVector<const Expr *, 4> InRedOps;
2875 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2876 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2877 auto IPriv = C->privates().begin();
2878 auto IRed = C->reduction_ops().begin();
2879 auto ITD = C->taskgroup_descriptors().begin();
2880 for (const auto *Ref : C->varlists()) {
2881 InRedVars.emplace_back(Ref);
2882 InRedPrivs.emplace_back(*IPriv);
2883 InRedOps.emplace_back(*IRed);
2884 TaskgroupDescriptors.emplace_back(*ITD);
2885 std::advance(IPriv, 1);
2886 std::advance(IRed, 1);
2887 std::advance(ITD, 1);
2888 }
2889 }
2890 // Privatize in_reduction items here, because taskgroup descriptors must be
2891 // privatized earlier.
2892 OMPPrivateScope InRedScope(CGF);
2893 if (!InRedVars.empty()) {
2894 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2895 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2896 RedCG.emitSharedLValue(CGF, Cnt);
2897 RedCG.emitAggregateType(CGF, Cnt);
2898 // The taskgroup descriptor variable is always implicit firstprivate and
2899 // privatized already during procoessing of the firstprivates.
2900 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2901 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2902 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2903 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2904 Replacement = Address(
2905 CGF.EmitScalarConversion(
2906 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2907 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2908 SourceLocation()),
2909 Replacement.getAlignment());
2910 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2911 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2912 [Replacement]() { return Replacement; });
2913 // FIXME: This must removed once the runtime library is fixed.
2914 // Emit required threadprivate variables for
2915 // initilizer/combiner/finalizer.
2916 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2917 RedCG, Cnt);
2918 }
2919 }
2920 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002921
2922 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002923 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002924 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002925 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2926 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2927 Data.NumberOfParts);
2928 OMPLexicalScope Scope(*this, S);
2929 TaskGen(*this, OutlinedFn, Data);
2930}
2931
2932void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2933 // Emit outlined function for task construct.
2934 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2935 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002936 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002937 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002938 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2939 if (C->getNameModifier() == OMPD_unknown ||
2940 C->getNameModifier() == OMPD_task) {
2941 IfCond = C->getCondition();
2942 break;
2943 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002944 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002945
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002946 OMPTaskDataTy Data;
2947 // Check if we should emit tied or untied task.
2948 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002949 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2950 CGF.EmitStmt(CS->getCapturedStmt());
2951 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002952 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002953 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002954 const OMPTaskDataTy &Data) {
2955 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2956 SharedsTy, CapturedStruct, IfCond,
2957 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002958 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002959 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002960}
2961
Alexey Bataev9f797f32015-02-05 05:57:51 +00002962void CodeGenFunction::EmitOMPTaskyieldDirective(
2963 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002964 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002965}
2966
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002967void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002968 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002969}
2970
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002971void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2972 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002973}
2974
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002975void CodeGenFunction::EmitOMPTaskgroupDirective(
2976 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002977 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2978 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002979 if (const Expr *E = S.getReductionRef()) {
2980 SmallVector<const Expr *, 4> LHSs;
2981 SmallVector<const Expr *, 4> RHSs;
2982 OMPTaskDataTy Data;
2983 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2984 auto IPriv = C->privates().begin();
2985 auto IRed = C->reduction_ops().begin();
2986 auto ILHS = C->lhs_exprs().begin();
2987 auto IRHS = C->rhs_exprs().begin();
2988 for (const auto *Ref : C->varlists()) {
2989 Data.ReductionVars.emplace_back(Ref);
2990 Data.ReductionCopies.emplace_back(*IPriv);
2991 Data.ReductionOps.emplace_back(*IRed);
2992 LHSs.emplace_back(*ILHS);
2993 RHSs.emplace_back(*IRHS);
2994 std::advance(IPriv, 1);
2995 std::advance(IRed, 1);
2996 std::advance(ILHS, 1);
2997 std::advance(IRHS, 1);
2998 }
2999 }
3000 llvm::Value *ReductionDesc =
3001 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3002 LHSs, RHSs, Data);
3003 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3004 CGF.EmitVarDecl(*VD);
3005 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3006 /*Volatile=*/false, E->getType());
3007 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003008 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003009 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003010 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003011 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3012}
3013
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003014void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003015 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003016 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003017 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3018 FlushClause->varlist_end());
3019 }
3020 return llvm::None;
3021 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003022}
3023
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003024void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3025 const CodeGenLoopTy &CodeGenLoop,
3026 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003027 // Emit the loop iteration variable.
3028 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3029 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3030 EmitVarDecl(*IVDecl);
3031
3032 // Emit the iterations count variable.
3033 // If it is not a variable, Sema decided to calculate iterations count on each
3034 // iteration (e.g., it is foldable into a constant).
3035 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3036 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3037 // Emit calculation of the iterations count.
3038 EmitIgnoredExpr(S.getCalcLastIteration());
3039 }
3040
3041 auto &RT = CGM.getOpenMPRuntime();
3042
Carlo Bertolli962bb802017-01-03 18:24:42 +00003043 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003044 // Check pre-condition.
3045 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003046 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003047 // Skip the entire loop if we don't meet the precondition.
3048 // If the condition constant folds and can be elided, avoid emitting the
3049 // whole loop.
3050 bool CondConstant;
3051 llvm::BasicBlock *ContBlock = nullptr;
3052 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3053 if (!CondConstant)
3054 return;
3055 } else {
3056 auto *ThenBlock = createBasicBlock("omp.precond.then");
3057 ContBlock = createBasicBlock("omp.precond.end");
3058 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3059 getProfileCount(&S));
3060 EmitBlock(ThenBlock);
3061 incrementProfileCounter(&S);
3062 }
3063
3064 // Emit 'then' code.
3065 {
3066 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003067
3068 LValue LB = EmitOMPHelperVar(
3069 *this, cast<DeclRefExpr>(
3070 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3071 ? S.getCombinedLowerBoundVariable()
3072 : S.getLowerBoundVariable())));
3073 LValue UB = EmitOMPHelperVar(
3074 *this, cast<DeclRefExpr>(
3075 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3076 ? S.getCombinedUpperBoundVariable()
3077 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003078 LValue ST =
3079 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3080 LValue IL =
3081 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3082
3083 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003084 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3085 // Emit implicit barrier to synchronize threads and avoid data races on
3086 // initialization of firstprivate variables and post-update of
3087 // lastprivate variables.
3088 CGM.getOpenMPRuntime().emitBarrierCall(
3089 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3090 /*ForceSimpleCall=*/true);
3091 }
3092 EmitOMPPrivateClause(S, LoopScope);
3093 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003094 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003095 (void)LoopScope.Privatize();
3096
3097 // Detect the distribute schedule kind and chunk.
3098 llvm::Value *Chunk = nullptr;
3099 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3100 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3101 ScheduleKind = C->getDistScheduleKind();
3102 if (const auto *Ch = C->getChunkSize()) {
3103 Chunk = EmitScalarExpr(Ch);
3104 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3105 S.getIterationVariable()->getType(),
3106 S.getLocStart());
3107 }
3108 }
3109 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3110 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3111
3112 // OpenMP [2.10.8, distribute Construct, Description]
3113 // If dist_schedule is specified, kind must be static. If specified,
3114 // iterations are divided into chunks of size chunk_size, chunks are
3115 // assigned to the teams of the league in a round-robin fashion in the
3116 // order of the team number. When no chunk_size is specified, the
3117 // iteration space is divided into chunks that are approximately equal
3118 // in size, and at most one chunk is distributed to each team of the
3119 // league. The size of the chunks is unspecified in this case.
3120 if (RT.isStaticNonchunked(ScheduleKind,
3121 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003122 CGOpenMPRuntime::StaticRTInput StaticInit(
3123 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3124 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003125 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003126 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003127 auto LoopExit =
3128 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3129 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003130 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3131 ? S.getCombinedEnsureUpperBound()
3132 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003133 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003134 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3135 ? S.getCombinedInit()
3136 : S.getInit());
3137
3138 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3139 ? S.getCombinedCond()
3140 : S.getCond();
3141
3142 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003143 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003144 // when combined with 'for' (e.g. as in 'distribute parallel for')
3145 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3146 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3147 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3148 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149 },
3150 [](CodeGenFunction &) {});
3151 EmitBlock(LoopExit.getBlock());
3152 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003153 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003154 } else {
3155 // Emit the outer loop, which requests its work chunk [LB..UB] from
3156 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003157 const OMPLoopArguments LoopArguments = {
3158 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3159 Chunk};
3160 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3161 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003162 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003163
3164 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3165 if (HasLastprivateClause)
3166 EmitOMPLastprivateClauseFinal(
3167 S, /*NoFinals=*/false,
3168 Builder.CreateIsNotNull(
3169 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003170 }
3171
3172 // We're now done with the loop, so jump to the continuation block.
3173 if (ContBlock) {
3174 EmitBranch(ContBlock);
3175 EmitBlock(ContBlock, true);
3176 }
3177 }
3178}
3179
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003180void CodeGenFunction::EmitOMPDistributeDirective(
3181 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003182 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003183
3184 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003185 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003186 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003187 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3188 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003189}
3190
Alexey Bataev5f600d62015-09-29 03:48:57 +00003191static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3192 const CapturedStmt *S) {
3193 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3194 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3195 CGF.CapturedStmtInfo = &CapStmtInfo;
3196 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3197 Fn->addFnAttr(llvm::Attribute::NoInline);
3198 return Fn;
3199}
3200
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003201void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003202 if (!S.getAssociatedStmt()) {
3203 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3204 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003205 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003206 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003207 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003208 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3209 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003210 if (C) {
3211 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3212 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3213 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3214 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003215 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3216 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003217 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003218 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003219 CGF.EmitStmt(
3220 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3221 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003222 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003223 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003224 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003225}
3226
Alexey Bataevb57056f2015-01-22 06:17:56 +00003227static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003228 QualType SrcType, QualType DestType,
3229 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003230 assert(CGF.hasScalarEvaluationKind(DestType) &&
3231 "DestType must have scalar evaluation kind.");
3232 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3233 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003234 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3235 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003236 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003237 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003238}
3239
3240static CodeGenFunction::ComplexPairTy
3241convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003242 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003243 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3244 "DestType must have complex evaluation kind.");
3245 CodeGenFunction::ComplexPairTy ComplexVal;
3246 if (Val.isScalar()) {
3247 // Convert the input element to the element type of the complex.
3248 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003249 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3250 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003251 ComplexVal = CodeGenFunction::ComplexPairTy(
3252 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3253 } else {
3254 assert(Val.isComplex() && "Must be a scalar or complex.");
3255 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3256 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3257 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003258 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003259 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003260 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003261 }
3262 return ComplexVal;
3263}
3264
Alexey Bataev5e018f92015-04-23 06:35:10 +00003265static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3266 LValue LVal, RValue RVal) {
3267 if (LVal.isGlobalReg()) {
3268 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3269 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003270 CGF.EmitAtomicStore(RVal, LVal,
3271 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3272 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003273 LVal.isVolatile(), /*IsInit=*/false);
3274 }
3275}
3276
Alexey Bataev8524d152016-01-21 12:35:58 +00003277void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3278 QualType RValTy, SourceLocation Loc) {
3279 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003280 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003281 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3282 *this, RVal, RValTy, LVal.getType(), Loc)),
3283 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003284 break;
3285 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003286 EmitStoreOfComplex(
3287 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003288 /*isInit=*/false);
3289 break;
3290 case TEK_Aggregate:
3291 llvm_unreachable("Must be a scalar or complex.");
3292 }
3293}
3294
Alexey Bataevb57056f2015-01-22 06:17:56 +00003295static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3296 const Expr *X, const Expr *V,
3297 SourceLocation Loc) {
3298 // v = x;
3299 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3300 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3301 LValue XLValue = CGF.EmitLValue(X);
3302 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003303 RValue Res = XLValue.isGlobalReg()
3304 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003305 : CGF.EmitAtomicLoad(
3306 XLValue, Loc,
3307 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3308 : llvm::AtomicOrdering::Monotonic,
3309 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003310 // OpenMP, 2.12.6, atomic Construct
3311 // Any atomic construct with a seq_cst clause forces the atomically
3312 // performed operation to include an implicit flush operation without a
3313 // list.
3314 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003315 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003316 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003317}
3318
Alexey Bataevb8329262015-02-27 06:33:30 +00003319static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3320 const Expr *X, const Expr *E,
3321 SourceLocation Loc) {
3322 // x = expr;
3323 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003324 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003325 // OpenMP, 2.12.6, atomic Construct
3326 // Any atomic construct with a seq_cst clause forces the atomically
3327 // performed operation to include an implicit flush operation without a
3328 // list.
3329 if (IsSeqCst)
3330 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3331}
3332
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003333static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3334 RValue Update,
3335 BinaryOperatorKind BO,
3336 llvm::AtomicOrdering AO,
3337 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003338 auto &Context = CGF.CGM.getContext();
3339 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003340 // expression is simple and atomic is allowed for the given type for the
3341 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003342 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003343 !Update.getScalarVal()->getType()->isIntegerTy() ||
3344 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3345 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003346 X.getAddress().getElementType())) ||
3347 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003348 !Context.getTargetInfo().hasBuiltinAtomic(
3349 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003350 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003351
3352 llvm::AtomicRMWInst::BinOp RMWOp;
3353 switch (BO) {
3354 case BO_Add:
3355 RMWOp = llvm::AtomicRMWInst::Add;
3356 break;
3357 case BO_Sub:
3358 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003359 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003360 RMWOp = llvm::AtomicRMWInst::Sub;
3361 break;
3362 case BO_And:
3363 RMWOp = llvm::AtomicRMWInst::And;
3364 break;
3365 case BO_Or:
3366 RMWOp = llvm::AtomicRMWInst::Or;
3367 break;
3368 case BO_Xor:
3369 RMWOp = llvm::AtomicRMWInst::Xor;
3370 break;
3371 case BO_LT:
3372 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3373 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3374 : llvm::AtomicRMWInst::Max)
3375 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3376 : llvm::AtomicRMWInst::UMax);
3377 break;
3378 case BO_GT:
3379 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3380 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3381 : llvm::AtomicRMWInst::Min)
3382 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3383 : llvm::AtomicRMWInst::UMin);
3384 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003385 case BO_Assign:
3386 RMWOp = llvm::AtomicRMWInst::Xchg;
3387 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003388 case BO_Mul:
3389 case BO_Div:
3390 case BO_Rem:
3391 case BO_Shl:
3392 case BO_Shr:
3393 case BO_LAnd:
3394 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003395 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003396 case BO_PtrMemD:
3397 case BO_PtrMemI:
3398 case BO_LE:
3399 case BO_GE:
3400 case BO_EQ:
3401 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003402 case BO_AddAssign:
3403 case BO_SubAssign:
3404 case BO_AndAssign:
3405 case BO_OrAssign:
3406 case BO_XorAssign:
3407 case BO_MulAssign:
3408 case BO_DivAssign:
3409 case BO_RemAssign:
3410 case BO_ShlAssign:
3411 case BO_ShrAssign:
3412 case BO_Comma:
3413 llvm_unreachable("Unsupported atomic update operation");
3414 }
3415 auto *UpdateVal = Update.getScalarVal();
3416 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3417 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003418 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003419 X.getType()->hasSignedIntegerRepresentation());
3420 }
John McCall7f416cc2015-09-08 08:05:57 +00003421 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003422 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003423}
3424
Alexey Bataev5e018f92015-04-23 06:35:10 +00003425std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003426 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3427 llvm::AtomicOrdering AO, SourceLocation Loc,
3428 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3429 // Update expressions are allowed to have the following forms:
3430 // x binop= expr; -> xrval + expr;
3431 // x++, ++x -> xrval + 1;
3432 // x--, --x -> xrval - 1;
3433 // x = x binop expr; -> xrval binop expr
3434 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003435 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3436 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003437 if (X.isGlobalReg()) {
3438 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3439 // 'xrval'.
3440 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3441 } else {
3442 // Perform compare-and-swap procedure.
3443 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003444 }
3445 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003446 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003447}
3448
3449static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3450 const Expr *X, const Expr *E,
3451 const Expr *UE, bool IsXLHSInRHSPart,
3452 SourceLocation Loc) {
3453 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3454 "Update expr in 'atomic update' must be a binary operator.");
3455 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3456 // Update expressions are allowed to have the following forms:
3457 // x binop= expr; -> xrval + expr;
3458 // x++, ++x -> xrval + 1;
3459 // x--, --x -> xrval - 1;
3460 // x = x binop expr; -> xrval binop expr
3461 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003462 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003463 LValue XLValue = CGF.EmitLValue(X);
3464 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003465 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3466 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003467 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3468 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3469 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3470 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3471 auto Gen =
3472 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3473 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3474 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3475 return CGF.EmitAnyExpr(UE);
3476 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003477 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3478 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3479 // OpenMP, 2.12.6, atomic Construct
3480 // Any atomic construct with a seq_cst clause forces the atomically
3481 // performed operation to include an implicit flush operation without a
3482 // list.
3483 if (IsSeqCst)
3484 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3485}
3486
3487static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003488 QualType SourceType, QualType ResType,
3489 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003490 switch (CGF.getEvaluationKind(ResType)) {
3491 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003492 return RValue::get(
3493 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003494 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003495 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003496 return RValue::getComplex(Res.first, Res.second);
3497 }
3498 case TEK_Aggregate:
3499 break;
3500 }
3501 llvm_unreachable("Must be a scalar or complex.");
3502}
3503
3504static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3505 bool IsPostfixUpdate, const Expr *V,
3506 const Expr *X, const Expr *E,
3507 const Expr *UE, bool IsXLHSInRHSPart,
3508 SourceLocation Loc) {
3509 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3510 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3511 RValue NewVVal;
3512 LValue VLValue = CGF.EmitLValue(V);
3513 LValue XLValue = CGF.EmitLValue(X);
3514 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003515 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3516 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003517 QualType NewVValType;
3518 if (UE) {
3519 // 'x' is updated with some additional value.
3520 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3521 "Update expr in 'atomic capture' must be a binary operator.");
3522 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3523 // Update expressions are allowed to have the following forms:
3524 // x binop= expr; -> xrval + expr;
3525 // x++, ++x -> xrval + 1;
3526 // x--, --x -> xrval - 1;
3527 // x = x binop expr; -> xrval binop expr
3528 // x = expr Op x; - > expr binop xrval;
3529 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3530 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3531 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3532 NewVValType = XRValExpr->getType();
3533 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3534 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003535 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003536 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3537 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3538 RValue Res = CGF.EmitAnyExpr(UE);
3539 NewVVal = IsPostfixUpdate ? XRValue : Res;
3540 return Res;
3541 };
3542 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3543 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3544 if (Res.first) {
3545 // 'atomicrmw' instruction was generated.
3546 if (IsPostfixUpdate) {
3547 // Use old value from 'atomicrmw'.
3548 NewVVal = Res.second;
3549 } else {
3550 // 'atomicrmw' does not provide new value, so evaluate it using old
3551 // value of 'x'.
3552 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3553 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3554 NewVVal = CGF.EmitAnyExpr(UE);
3555 }
3556 }
3557 } else {
3558 // 'x' is simply rewritten with some 'expr'.
3559 NewVValType = X->getType().getNonReferenceType();
3560 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003561 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003562 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003563 NewVVal = XRValue;
3564 return ExprRValue;
3565 };
3566 // Try to perform atomicrmw xchg, otherwise simple exchange.
3567 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3568 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3569 Loc, Gen);
3570 if (Res.first) {
3571 // 'atomicrmw' instruction was generated.
3572 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3573 }
3574 }
3575 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003576 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003577 // OpenMP, 2.12.6, atomic Construct
3578 // Any atomic construct with a seq_cst clause forces the atomically
3579 // performed operation to include an implicit flush operation without a
3580 // list.
3581 if (IsSeqCst)
3582 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3583}
3584
Alexey Bataevb57056f2015-01-22 06:17:56 +00003585static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003586 bool IsSeqCst, bool IsPostfixUpdate,
3587 const Expr *X, const Expr *V, const Expr *E,
3588 const Expr *UE, bool IsXLHSInRHSPart,
3589 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003590 switch (Kind) {
3591 case OMPC_read:
3592 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3593 break;
3594 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003595 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3596 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003597 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003598 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003599 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3600 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003601 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003602 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3603 IsXLHSInRHSPart, Loc);
3604 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003605 case OMPC_if:
3606 case OMPC_final:
3607 case OMPC_num_threads:
3608 case OMPC_private:
3609 case OMPC_firstprivate:
3610 case OMPC_lastprivate:
3611 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003612 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003613 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003614 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003615 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003616 case OMPC_collapse:
3617 case OMPC_default:
3618 case OMPC_seq_cst:
3619 case OMPC_shared:
3620 case OMPC_linear:
3621 case OMPC_aligned:
3622 case OMPC_copyin:
3623 case OMPC_copyprivate:
3624 case OMPC_flush:
3625 case OMPC_proc_bind:
3626 case OMPC_schedule:
3627 case OMPC_ordered:
3628 case OMPC_nowait:
3629 case OMPC_untied:
3630 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003631 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003632 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003633 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003634 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003635 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003636 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003637 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003638 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003639 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003640 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003641 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003642 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003643 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003644 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003645 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003646 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003647 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003648 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003649 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003650 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003651 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3652 }
3653}
3654
3655void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003656 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003657 OpenMPClauseKind Kind = OMPC_unknown;
3658 for (auto *C : S.clauses()) {
3659 // Find first clause (skip seq_cst clause, if it is first).
3660 if (C->getClauseKind() != OMPC_seq_cst) {
3661 Kind = C->getClauseKind();
3662 break;
3663 }
3664 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003665
3666 const auto *CS =
3667 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003668 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003669 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003670 }
3671 // Processing for statements under 'atomic capture'.
3672 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3673 for (const auto *C : Compound->body()) {
3674 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3675 enterFullExpression(EWC);
3676 }
3677 }
3678 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003679
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003680 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3681 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003682 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003683 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3684 S.getV(), S.getExpr(), S.getUpdateExpr(),
3685 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003686 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003687 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003688 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003689}
3690
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003691static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3692 const OMPExecutableDirective &S,
3693 const RegionCodeGenTy &CodeGen) {
3694 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3695 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003696 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003697
Samuel Antaoee8fb302016-01-06 13:42:12 +00003698 llvm::Function *Fn = nullptr;
3699 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003700
Samuel Antaobed3c462015-10-02 16:14:20 +00003701 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003702 // Check for the at most one if clause associated with the target region.
3703 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3704 if (C->getNameModifier() == OMPD_unknown ||
3705 C->getNameModifier() == OMPD_target) {
3706 IfCond = C->getCondition();
3707 break;
3708 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003709 }
3710
3711 // Check if we have any device clause associated with the directive.
3712 const Expr *Device = nullptr;
3713 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3714 Device = C->getDevice();
3715 }
3716
Samuel Antaoee8fb302016-01-06 13:42:12 +00003717 // Check if we have an if clause whose conditional always evaluates to false
3718 // or if we do not have any targets specified. If so the target region is not
3719 // an offload entry point.
3720 bool IsOffloadEntry = true;
3721 if (IfCond) {
3722 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003723 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003724 IsOffloadEntry = false;
3725 }
3726 if (CGM.getLangOpts().OMPTargetTriples.empty())
3727 IsOffloadEntry = false;
3728
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003729 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003730 StringRef ParentName;
3731 // In case we have Ctors/Dtors we use the complete type variant to produce
3732 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003733 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003734 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003735 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003736 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3737 else
3738 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003739 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003741 // Emit target region as a standalone region.
3742 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3743 IsOffloadEntry, CodeGen);
3744 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003745 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3746 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003747 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003748 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003749}
3750
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003751static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3752 PrePostActionTy &Action) {
3753 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3754 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3755 CGF.EmitOMPPrivateClause(S, PrivateScope);
3756 (void)PrivateScope.Privatize();
3757
3758 Action.Enter(CGF);
3759 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3760}
3761
3762void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3763 StringRef ParentName,
3764 const OMPTargetDirective &S) {
3765 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3766 emitTargetRegion(CGF, S, Action);
3767 };
3768 llvm::Function *Fn;
3769 llvm::Constant *Addr;
3770 // Emit target region as a standalone region.
3771 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3772 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3773 assert(Fn && Addr && "Target device function emission failed.");
3774}
3775
3776void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3777 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3778 emitTargetRegion(CGF, S, Action);
3779 };
3780 emitCommonOMPTargetDirective(*this, S, CodeGen);
3781}
3782
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003783static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3784 const OMPExecutableDirective &S,
3785 OpenMPDirectiveKind InnermostKind,
3786 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003787 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3788 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3789 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003790
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003791 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3792 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003793 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003794 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3795 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003796
Carlo Bertollic6872252016-04-04 15:55:02 +00003797 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3798 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003799 }
3800
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003801 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003802 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3803 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003804 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3805 CapturedVars);
3806}
3807
3808void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003809 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003810 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003811 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003812 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3813 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003814 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003815 (void)PrivateScope.Privatize();
3816 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003817 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003818 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003819 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003820 emitPostUpdateForReductionClause(
3821 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003822}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003823
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003824static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3825 const OMPTargetTeamsDirective &S) {
3826 auto *CS = S.getCapturedStmt(OMPD_teams);
3827 Action.Enter(CGF);
3828 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3829 // TODO: Add support for clauses.
3830 CGF.EmitStmt(CS->getCapturedStmt());
3831 };
3832 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3833}
3834
3835void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3836 CodeGenModule &CGM, StringRef ParentName,
3837 const OMPTargetTeamsDirective &S) {
3838 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3839 emitTargetTeamsRegion(CGF, Action, S);
3840 };
3841 llvm::Function *Fn;
3842 llvm::Constant *Addr;
3843 // Emit target region as a standalone region.
3844 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3845 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3846 assert(Fn && Addr && "Target device function emission failed.");
3847}
3848
3849void CodeGenFunction::EmitOMPTargetTeamsDirective(
3850 const OMPTargetTeamsDirective &S) {
3851 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3852 emitTargetTeamsRegion(CGF, Action, S);
3853 };
3854 emitCommonOMPTargetDirective(*this, S, CodeGen);
3855}
3856
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003857void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3858 const OMPTeamsDistributeDirective &S) {
3859
3860 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3861 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3862 };
3863
3864 // Emit teams region as a standalone region.
3865 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3866 PrePostActionTy &) {
3867 OMPPrivateScope PrivateScope(CGF);
3868 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3869 (void)PrivateScope.Privatize();
3870 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3871 CodeGenDistribute);
3872 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3873 };
3874 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
3875 emitPostUpdateForReductionClause(*this, S,
3876 [](CodeGenFunction &) { return nullptr; });
3877}
3878
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003879void CodeGenFunction::EmitOMPCancellationPointDirective(
3880 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003881 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3882 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003883}
3884
Alexey Bataev80909872015-07-02 11:25:17 +00003885void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003886 const Expr *IfCond = nullptr;
3887 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3888 if (C->getNameModifier() == OMPD_unknown ||
3889 C->getNameModifier() == OMPD_cancel) {
3890 IfCond = C->getCondition();
3891 break;
3892 }
3893 }
3894 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003895 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003896}
3897
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003898CodeGenFunction::JumpDest
3899CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003900 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3901 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003902 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003903 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003904 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3905 Kind == OMPD_distribute_parallel_for ||
3906 Kind == OMPD_target_parallel_for);
3907 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003908}
Michael Wong65f367f2015-07-21 13:44:28 +00003909
Samuel Antaocc10b852016-07-28 14:23:26 +00003910void CodeGenFunction::EmitOMPUseDevicePtrClause(
3911 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3912 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3913 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3914 auto OrigVarIt = C.varlist_begin();
3915 auto InitIt = C.inits().begin();
3916 for (auto PvtVarIt : C.private_copies()) {
3917 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3918 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3919 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3920
3921 // In order to identify the right initializer we need to match the
3922 // declaration used by the mapping logic. In some cases we may get
3923 // OMPCapturedExprDecl that refers to the original declaration.
3924 const ValueDecl *MatchingVD = OrigVD;
3925 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3926 // OMPCapturedExprDecl are used to privative fields of the current
3927 // structure.
3928 auto *ME = cast<MemberExpr>(OED->getInit());
3929 assert(isa<CXXThisExpr>(ME->getBase()) &&
3930 "Base should be the current struct!");
3931 MatchingVD = ME->getMemberDecl();
3932 }
3933
3934 // If we don't have information about the current list item, move on to
3935 // the next one.
3936 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3937 if (InitAddrIt == CaptureDeviceAddrMap.end())
3938 continue;
3939
3940 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3941 // Initialize the temporary initialization variable with the address we
3942 // get from the runtime library. We have to cast the source address
3943 // because it is always a void *. References are materialized in the
3944 // privatization scope, so the initialization here disregards the fact
3945 // the original variable is a reference.
3946 QualType AddrQTy =
3947 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3948 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3949 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3950 setAddrOfLocalVar(InitVD, InitAddr);
3951
3952 // Emit private declaration, it will be initialized by the value we
3953 // declaration we just added to the local declarations map.
3954 EmitDecl(*PvtVD);
3955
3956 // The initialization variables reached its purpose in the emission
3957 // ofthe previous declaration, so we don't need it anymore.
3958 LocalDeclMap.erase(InitVD);
3959
3960 // Return the address of the private variable.
3961 return GetAddrOfLocalVar(PvtVD);
3962 });
3963 assert(IsRegistered && "firstprivate var already registered as private");
3964 // Silence the warning about unused variable.
3965 (void)IsRegistered;
3966
3967 ++OrigVarIt;
3968 ++InitIt;
3969 }
3970}
3971
Michael Wong65f367f2015-07-21 13:44:28 +00003972// Generate the instructions for '#pragma omp target data' directive.
3973void CodeGenFunction::EmitOMPTargetDataDirective(
3974 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003975 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3976
3977 // Create a pre/post action to signal the privatization of the device pointer.
3978 // This action can be replaced by the OpenMP runtime code generation to
3979 // deactivate privatization.
3980 bool PrivatizeDevicePointers = false;
3981 class DevicePointerPrivActionTy : public PrePostActionTy {
3982 bool &PrivatizeDevicePointers;
3983
3984 public:
3985 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3986 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3987 void Enter(CodeGenFunction &CGF) override {
3988 PrivatizeDevicePointers = true;
3989 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003990 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003991 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3992
3993 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3994 CodeGenFunction &CGF, PrePostActionTy &Action) {
3995 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3996 CGF.EmitStmt(
3997 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3998 };
3999
4000 // Codegen that selects wheather to generate the privatization code or not.
4001 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4002 &InnermostCodeGen](CodeGenFunction &CGF,
4003 PrePostActionTy &Action) {
4004 RegionCodeGenTy RCG(InnermostCodeGen);
4005 PrivatizeDevicePointers = false;
4006
4007 // Call the pre-action to change the status of PrivatizeDevicePointers if
4008 // needed.
4009 Action.Enter(CGF);
4010
4011 if (PrivatizeDevicePointers) {
4012 OMPPrivateScope PrivateScope(CGF);
4013 // Emit all instances of the use_device_ptr clause.
4014 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4015 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4016 Info.CaptureDeviceAddrMap);
4017 (void)PrivateScope.Privatize();
4018 RCG(CGF);
4019 } else
4020 RCG(CGF);
4021 };
4022
4023 // Forward the provided action to the privatization codegen.
4024 RegionCodeGenTy PrivRCG(PrivCodeGen);
4025 PrivRCG.setAction(Action);
4026
4027 // Notwithstanding the body of the region is emitted as inlined directive,
4028 // we don't use an inline scope as changes in the references inside the
4029 // region are expected to be visible outside, so we do not privative them.
4030 OMPLexicalScope Scope(CGF, S);
4031 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4032 PrivRCG);
4033 };
4034
4035 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004036
4037 // If we don't have target devices, don't bother emitting the data mapping
4038 // code.
4039 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004040 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004041 return;
4042 }
4043
4044 // Check if we have any if clause associated with the directive.
4045 const Expr *IfCond = nullptr;
4046 if (auto *C = S.getSingleClause<OMPIfClause>())
4047 IfCond = C->getCondition();
4048
4049 // Check if we have any device clause associated with the directive.
4050 const Expr *Device = nullptr;
4051 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4052 Device = C->getDevice();
4053
Samuel Antaocc10b852016-07-28 14:23:26 +00004054 // Set the action to signal privatization of device pointers.
4055 RCG.setAction(PrivAction);
4056
4057 // Emit region code.
4058 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4059 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004060}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004061
Samuel Antaodf67fc42016-01-19 19:15:56 +00004062void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4063 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004064 // If we don't have target devices, don't bother emitting the data mapping
4065 // code.
4066 if (CGM.getLangOpts().OMPTargetTriples.empty())
4067 return;
4068
4069 // Check if we have any if clause associated with the directive.
4070 const Expr *IfCond = nullptr;
4071 if (auto *C = S.getSingleClause<OMPIfClause>())
4072 IfCond = C->getCondition();
4073
4074 // Check if we have any device clause associated with the directive.
4075 const Expr *Device = nullptr;
4076 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4077 Device = C->getDevice();
4078
Samuel Antao8d2d7302016-05-26 18:30:22 +00004079 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004080}
4081
Samuel Antao72590762016-01-19 20:04:50 +00004082void CodeGenFunction::EmitOMPTargetExitDataDirective(
4083 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004084 // If we don't have target devices, don't bother emitting the data mapping
4085 // code.
4086 if (CGM.getLangOpts().OMPTargetTriples.empty())
4087 return;
4088
4089 // Check if we have any if clause associated with the directive.
4090 const Expr *IfCond = nullptr;
4091 if (auto *C = S.getSingleClause<OMPIfClause>())
4092 IfCond = C->getCondition();
4093
4094 // Check if we have any device clause associated with the directive.
4095 const Expr *Device = nullptr;
4096 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4097 Device = C->getDevice();
4098
Samuel Antao8d2d7302016-05-26 18:30:22 +00004099 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004100}
4101
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004102static void emitTargetParallelRegion(CodeGenFunction &CGF,
4103 const OMPTargetParallelDirective &S,
4104 PrePostActionTy &Action) {
4105 // Get the captured statement associated with the 'parallel' region.
4106 auto *CS = S.getCapturedStmt(OMPD_parallel);
4107 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004108 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4109 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4110 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4111 CGF.EmitOMPPrivateClause(S, PrivateScope);
4112 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4113 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004114 // TODO: Add support for clauses.
4115 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004116 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004117 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004118 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4119 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004120 emitPostUpdateForReductionClause(
4121 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004122}
4123
4124void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4125 CodeGenModule &CGM, StringRef ParentName,
4126 const OMPTargetParallelDirective &S) {
4127 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4128 emitTargetParallelRegion(CGF, S, Action);
4129 };
4130 llvm::Function *Fn;
4131 llvm::Constant *Addr;
4132 // Emit target region as a standalone region.
4133 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4134 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4135 assert(Fn && Addr && "Target device function emission failed.");
4136}
4137
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004138void CodeGenFunction::EmitOMPTargetParallelDirective(
4139 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004140 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4141 emitTargetParallelRegion(CGF, S, Action);
4142 };
4143 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004144}
4145
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004146static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4147 const OMPTargetParallelForDirective &S,
4148 PrePostActionTy &Action) {
4149 Action.Enter(CGF);
4150 // Emit directive as a combined directive that consists of two implicit
4151 // directives: 'parallel' with 'for' directive.
4152 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004153 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4154 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004155 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4156 emitDispatchForLoopBounds);
4157 };
4158 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4159 emitEmptyBoundParameters);
4160}
4161
4162void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4163 CodeGenModule &CGM, StringRef ParentName,
4164 const OMPTargetParallelForDirective &S) {
4165 // Emit SPMD target parallel for region as a standalone region.
4166 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4167 emitTargetParallelForRegion(CGF, S, Action);
4168 };
4169 llvm::Function *Fn;
4170 llvm::Constant *Addr;
4171 // Emit target region as a standalone region.
4172 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4173 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4174 assert(Fn && Addr && "Target device function emission failed.");
4175}
4176
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004177void CodeGenFunction::EmitOMPTargetParallelForDirective(
4178 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004179 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4180 emitTargetParallelForRegion(CGF, S, Action);
4181 };
4182 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004183}
4184
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004185static void
4186emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4187 const OMPTargetParallelForSimdDirective &S,
4188 PrePostActionTy &Action) {
4189 Action.Enter(CGF);
4190 // Emit directive as a combined directive that consists of two implicit
4191 // directives: 'parallel' with 'for' directive.
4192 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4193 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4194 emitDispatchForLoopBounds);
4195 };
4196 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4197 emitEmptyBoundParameters);
4198}
4199
4200void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4201 CodeGenModule &CGM, StringRef ParentName,
4202 const OMPTargetParallelForSimdDirective &S) {
4203 // Emit SPMD target parallel for region as a standalone region.
4204 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4205 emitTargetParallelForSimdRegion(CGF, S, Action);
4206 };
4207 llvm::Function *Fn;
4208 llvm::Constant *Addr;
4209 // Emit target region as a standalone region.
4210 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4211 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4212 assert(Fn && Addr && "Target device function emission failed.");
4213}
4214
4215void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4216 const OMPTargetParallelForSimdDirective &S) {
4217 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4218 emitTargetParallelForSimdRegion(CGF, S, Action);
4219 };
4220 emitCommonOMPTargetDirective(*this, S, CodeGen);
4221}
4222
Alexey Bataev7292c292016-04-25 12:22:29 +00004223/// Emit a helper variable and return corresponding lvalue.
4224static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4225 const ImplicitParamDecl *PVD,
4226 CodeGenFunction::OMPPrivateScope &Privates) {
4227 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4228 Privates.addPrivate(
4229 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4230}
4231
4232void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4233 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4234 // Emit outlined function for task construct.
4235 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4236 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4237 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4238 const Expr *IfCond = nullptr;
4239 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4240 if (C->getNameModifier() == OMPD_unknown ||
4241 C->getNameModifier() == OMPD_taskloop) {
4242 IfCond = C->getCondition();
4243 break;
4244 }
4245 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004246
4247 OMPTaskDataTy Data;
4248 // Check if taskloop must be emitted without taskgroup.
4249 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004250 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004251 Data.Tied = true;
4252 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004253 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4254 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004255 Data.Schedule.setInt(/*IntVal=*/false);
4256 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004257 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4258 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004259 Data.Schedule.setInt(/*IntVal=*/true);
4260 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004261 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004262
4263 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4264 // if (PreCond) {
4265 // for (IV in 0..LastIteration) BODY;
4266 // <Final counter/linear vars updates>;
4267 // }
4268 //
4269
4270 // Emit: if (PreCond) - begin.
4271 // If the condition constant folds and can be elided, avoid emitting the
4272 // whole loop.
4273 bool CondConstant;
4274 llvm::BasicBlock *ContBlock = nullptr;
4275 OMPLoopScope PreInitScope(CGF, S);
4276 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4277 if (!CondConstant)
4278 return;
4279 } else {
4280 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4281 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4282 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4283 CGF.getProfileCount(&S));
4284 CGF.EmitBlock(ThenBlock);
4285 CGF.incrementProfileCounter(&S);
4286 }
4287
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004288 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4289 CGF.EmitOMPSimdInit(S);
4290
Alexey Bataev7292c292016-04-25 12:22:29 +00004291 OMPPrivateScope LoopScope(CGF);
4292 // Emit helper vars inits.
4293 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4294 auto *I = CS->getCapturedDecl()->param_begin();
4295 auto *LBP = std::next(I, LowerBound);
4296 auto *UBP = std::next(I, UpperBound);
4297 auto *STP = std::next(I, Stride);
4298 auto *LIP = std::next(I, LastIter);
4299 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4300 LoopScope);
4301 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4302 LoopScope);
4303 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4304 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4305 LoopScope);
4306 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004307 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004308 (void)LoopScope.Privatize();
4309 // Emit the loop iteration variable.
4310 const Expr *IVExpr = S.getIterationVariable();
4311 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4312 CGF.EmitVarDecl(*IVDecl);
4313 CGF.EmitIgnoredExpr(S.getInit());
4314
4315 // Emit the iterations count variable.
4316 // If it is not a variable, Sema decided to calculate iterations count on
4317 // each iteration (e.g., it is foldable into a constant).
4318 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4319 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4320 // Emit calculation of the iterations count.
4321 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4322 }
4323
4324 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4325 S.getInc(),
4326 [&S](CodeGenFunction &CGF) {
4327 CGF.EmitOMPLoopBody(S, JumpDest());
4328 CGF.EmitStopPoint(&S);
4329 },
4330 [](CodeGenFunction &) {});
4331 // Emit: if (PreCond) - end.
4332 if (ContBlock) {
4333 CGF.EmitBranch(ContBlock);
4334 CGF.EmitBlock(ContBlock, true);
4335 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004336 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4337 if (HasLastprivateClause) {
4338 CGF.EmitOMPLastprivateClauseFinal(
4339 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4340 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4341 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4342 (*LIP)->getType(), S.getLocStart())));
4343 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004344 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004345 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4346 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4347 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004348 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4349 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004350 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4351 OutlinedFn, SharedsTy,
4352 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004353 };
4354 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4355 CodeGen);
4356 };
Alexey Bataev33446032017-07-12 18:09:32 +00004357 if (Data.Nogroup)
4358 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4359 else {
4360 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4361 *this,
4362 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4363 PrePostActionTy &Action) {
4364 Action.Enter(CGF);
4365 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4366 },
4367 S.getLocStart());
4368 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004369}
4370
Alexey Bataev49f6e782015-12-01 04:18:41 +00004371void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004372 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004373}
4374
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004375void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4376 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004377 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004378}
Samuel Antao686c70c2016-05-26 17:30:50 +00004379
4380// Generate the instructions for '#pragma omp target update' directive.
4381void CodeGenFunction::EmitOMPTargetUpdateDirective(
4382 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004383 // If we don't have target devices, don't bother emitting the data mapping
4384 // code.
4385 if (CGM.getLangOpts().OMPTargetTriples.empty())
4386 return;
4387
4388 // Check if we have any if clause associated with the directive.
4389 const Expr *IfCond = nullptr;
4390 if (auto *C = S.getSingleClause<OMPIfClause>())
4391 IfCond = C->getCondition();
4392
4393 // Check if we have any device clause associated with the directive.
4394 const Expr *Device = nullptr;
4395 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4396 Device = C->getDevice();
4397
4398 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004399}