blob: 22a36eb0b55548562763e87f12f809be6f68a9f4 [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 Bataevb45d43c2017-11-22 16:02:03 +0000314 FunctionDecl *DebugFunctionDecl = nullptr;
315 if (!FO.UIntPtrCastRequired) {
316 FunctionProtoType::ExtProtoInfo EPI;
317 DebugFunctionDecl = FunctionDecl::Create(
318 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
319 SourceLocation(), DeclarationName(), Ctx.VoidTy,
320 Ctx.getTrivialTypeSourceInfo(
321 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
322 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
323 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000324 for (auto *FD : RD->fields()) {
325 QualType ArgType = FD->getType();
326 IdentifierInfo *II = nullptr;
327 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000328
329 // If this is a capture by copy and the type is not a pointer, the outlined
330 // function argument type should be uintptr and the value properly casted to
331 // uintptr. This is necessary given that the runtime library is only able to
332 // deal with pointers. We can pass in the same way the VLA type sizes to the
333 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000334 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000335 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000336 if (FO.UIntPtrCastRequired)
337 ArgType = Ctx.getUIntPtrType();
338 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000339
340 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000341 CapVar = I->getCapturedVar();
342 II = CapVar->getIdentifier();
343 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000344 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000345 else {
346 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000347 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000348 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000349 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000350 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000351 VarDecl *Arg;
352 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
353 Arg = ParmVarDecl::Create(
354 Ctx, DebugFunctionDecl,
355 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
356 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
357 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
358 } else {
359 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
360 II, ArgType, ImplicitParamDecl::Other);
361 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000362 Args.emplace_back(Arg);
363 // Do not cast arguments if we emit function with non-original types.
364 TargetArgs.emplace_back(
365 FO.UIntPtrCastRequired
366 ? Arg
367 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000368 ++I;
369 }
370 Args.append(
371 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
372 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000373 TargetArgs.append(
374 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
375 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376
377 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000378 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000379 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000380 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
381
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000382 llvm::Function *F =
383 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
384 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000385 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
386 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000387 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000388
389 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000390 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
391 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000392 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000393 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000394 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000395 // Do not map arguments if we emit function with non-original types.
396 Address LocalAddr(Address::invalid());
397 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
398 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
399 TargetArgs[Cnt]);
400 } else {
401 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
402 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000403 // If we are capturing a pointer by copy we don't need to do anything, just
404 // use the value that we get from the arguments.
405 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000406 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000407 // If the variable is a reference we need to materialize it here.
408 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000409 Address RefAddr = CGF.CreateMemTemp(
410 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
411 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
412 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000413 LocalAddr = RefAddr;
414 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 if (!FO.RegisterCastedArgsOnly)
416 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000417 ++Cnt;
418 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000419 continue;
420 }
421
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000422 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
423 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000424 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000425 if (FO.UIntPtrCastRequired) {
426 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
427 Args[Cnt]->getName(),
428 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000429 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000430 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000431 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000432 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000433 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000434 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000435 } else if (I->capturesVariable()) {
436 auto *Var = I->getCapturedVar();
437 QualType VarTy = Var->getType();
438 Address ArgAddr = ArgLVal.getAddress();
439 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000440 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000441 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000442 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000443 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000444 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000445 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
446 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000447 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000448 if (!FO.RegisterCastedArgsOnly) {
449 LocalAddrs.insert(
450 {Args[Cnt],
451 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
452 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000453 } else if (I->capturesVariableByCopy()) {
454 assert(!FD->getType()->isAnyPointerType() &&
455 "Not expecting a captured pointer.");
456 auto *Var = I->getCapturedVar();
457 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000458 LocalAddrs.insert(
459 {Args[Cnt],
460 {Var,
461 FO.UIntPtrCastRequired
462 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
463 ArgLVal, VarTy->isReferenceType())
464 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 } else {
466 // If 'this' is captured, load it into CXXThisValue.
467 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000468 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
469 .getScalarVal();
470 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000471 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000472 ++Cnt;
473 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000474 }
475
Alexey Bataeve754b182017-08-09 19:38:53 +0000476 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000477}
478
479llvm::Function *
480CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
481 assert(
482 CapturedStmtInfo &&
483 "CapturedStmtInfo should be set when generating the captured function");
484 const CapturedDecl *CD = S.getCapturedDecl();
485 // Build the argument list.
486 bool NeedWrapperFunction =
487 getDebugInfo() &&
488 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
489 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000490 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000491 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000492 SmallString<256> Buffer;
493 llvm::raw_svector_ostream Out(Buffer);
494 Out << CapturedStmtInfo->getHelperName();
495 if (NeedWrapperFunction)
496 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000497 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000498 Out.str());
499 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
500 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 for (const auto &LocalAddrPair : LocalAddrs) {
502 if (LocalAddrPair.second.first) {
503 setAddrOfLocalVar(LocalAddrPair.second.first,
504 LocalAddrPair.second.second);
505 }
506 }
507 for (const auto &VLASizePair : VLASizes)
508 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000509 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000510 CapturedStmtInfo->EmitBody(*this, CD->getBody());
511 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000512 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000513 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000514
Alexey Bataevefd884d2017-08-04 21:26:25 +0000515 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000516 /*RegisterCastedArgsOnly=*/true,
517 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000518 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000519 Args.clear();
520 LocalAddrs.clear();
521 VLASizes.clear();
522 llvm::Function *WrapperF =
523 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000524 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000525 llvm::SmallVector<llvm::Value *, 4> CallArgs;
526 for (const auto *Arg : Args) {
527 llvm::Value *CallArg;
528 auto I = LocalAddrs.find(Arg);
529 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000530 LValue LV = WrapperCGF.MakeAddrLValue(
531 I->second.second,
532 I->second.first ? I->second.first->getType() : Arg->getType(),
533 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000534 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
535 } else {
536 auto EI = VLASizes.find(Arg);
537 if (EI != VLASizes.end())
538 CallArg = EI->second.second;
539 else {
540 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000541 Arg->getType(),
542 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000543 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
544 }
545 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000546 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000547 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000548 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
549 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000550 WrapperCGF.FinishFunction();
551 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000552}
553
Alexey Bataev9959db52014-05-06 10:08:46 +0000554//===----------------------------------------------------------------------===//
555// OpenMP Directive Emission
556//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000557void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000558 Address DestAddr, Address SrcAddr, QualType OriginalType,
559 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000560 // Perform element-by-element initialization.
561 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000562
563 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000564 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000565 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
566 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
567
568 auto SrcBegin = SrcAddr.getPointer();
569 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000570 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000571 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
572 // The basic structure here is a while-do loop.
573 auto BodyBB = createBasicBlock("omp.arraycpy.body");
574 auto DoneBB = createBasicBlock("omp.arraycpy.done");
575 auto IsEmpty =
576 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
577 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000578
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 // Enter the loop body, making that address the current address.
580 auto EntryBB = Builder.GetInsertBlock();
581 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000582
583 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
584
585 llvm::PHINode *SrcElementPHI =
586 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
587 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
588 Address SrcElementCurrent =
589 Address(SrcElementPHI,
590 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
591
592 llvm::PHINode *DestElementPHI =
593 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
594 DestElementPHI->addIncoming(DestBegin, EntryBB);
595 Address DestElementCurrent =
596 Address(DestElementPHI,
597 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000598
Alexey Bataev420d45b2015-04-14 05:11:24 +0000599 // Emit copy.
600 CopyGen(DestElementCurrent, SrcElementCurrent);
601
602 // Shift the address forward by one element.
603 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000604 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000605 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000606 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000607 // Check whether we've reached the end.
608 auto Done =
609 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
610 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000611 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
612 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000613
614 // Done.
615 EmitBlock(DoneBB, /*IsFinished=*/true);
616}
617
John McCall7f416cc2015-09-08 08:05:57 +0000618void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
619 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000620 const VarDecl *SrcVD, const Expr *Copy) {
621 if (OriginalType->isArrayType()) {
622 auto *BO = dyn_cast<BinaryOperator>(Copy);
623 if (BO && BO->getOpcode() == BO_Assign) {
624 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000625 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000626 } else {
627 // For arrays with complex element types perform element by element
628 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000629 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000631 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000632 // Working with the single array element, so have to remap
633 // destination and source variables to corresponding array
634 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000635 CodeGenFunction::OMPPrivateScope Remap(*this);
636 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000637 return DestElement;
638 });
639 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000640 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000642 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000644 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000645 } else {
646 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000647 CodeGenFunction::OMPPrivateScope Remap(*this);
648 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
649 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000650 (void)Remap.Privatize();
651 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000652 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000653 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000654}
655
Alexey Bataev69c62a92015-04-15 04:52:20 +0000656bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
657 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000658 if (!HaveInsertPoint())
659 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000660 bool FirstprivateIsLastprivate = false;
661 llvm::DenseSet<const VarDecl *> Lastprivates;
662 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
663 for (const auto *D : C->varlists())
664 Lastprivates.insert(
665 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
666 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000667 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000668 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000669 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000670 auto IRef = C->varlist_begin();
671 auto InitsRef = C->inits().begin();
672 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000673 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000674 bool ThisFirstprivateIsLastprivate =
675 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000676 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000677 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000678 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000679 !FD->getType()->isReferenceType()) {
680 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
681 ++IRef;
682 ++InitsRef;
683 continue;
684 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000685 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000687 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000688 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
689 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
690 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000691 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
692 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
693 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000694 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000695 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000696 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000697 // Emit VarDecl with copy init for arrays.
698 // Get the address of the original variable captured in current
699 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000700 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000701 auto Emission = EmitAutoVarAlloca(*VD);
702 auto *Init = VD->getInit();
703 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
704 // Perform simple memcpy.
705 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000706 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000707 } else {
708 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000709 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000710 [this, VDInit, Init](Address DestElement,
711 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000712 // Clean up any temporaries needed by the initialization.
713 RunCleanupsScope InitScope(*this);
714 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000715 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000716 EmitAnyExprToMem(Init, DestElement,
717 Init->getType().getQualifiers(),
718 /*IsInitializer*/ false);
719 LocalDeclMap.erase(VDInit);
720 });
721 }
722 EmitAutoVarCleanups(Emission);
723 return Emission.getAllocatedAddress();
724 });
725 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000726 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000727 // Emit private VarDecl with copy init.
728 // Remap temp VDInit variable to the address of the original
729 // variable
730 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000731 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000732 EmitDecl(*VD);
733 LocalDeclMap.erase(VDInit);
734 return GetAddrOfLocalVar(VD);
735 });
736 }
737 assert(IsRegistered &&
738 "firstprivate var already registered as private");
739 // Silence the warning about unused variable.
740 (void)IsRegistered;
741 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000742 ++IRef;
743 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000744 }
745 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000746 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000747}
748
Alexey Bataev03b340a2014-10-21 03:16:40 +0000749void CodeGenFunction::EmitOMPPrivateClause(
750 const OMPExecutableDirective &D,
751 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000752 if (!HaveInsertPoint())
753 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000754 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000755 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000756 auto IRef = C->varlist_begin();
757 for (auto IInit : C->private_copies()) {
758 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000759 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
760 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
761 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000762 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000763 // Emit private VarDecl with copy init.
764 EmitDecl(*VD);
765 return GetAddrOfLocalVar(VD);
766 });
767 assert(IsRegistered && "private var already registered as private");
768 // Silence the warning about unused variable.
769 (void)IsRegistered;
770 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000771 ++IRef;
772 }
773 }
774}
775
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000776bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000777 if (!HaveInsertPoint())
778 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000779 // threadprivate_var1 = master_threadprivate_var1;
780 // operator=(threadprivate_var2, master_threadprivate_var2);
781 // ...
782 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000783 llvm::DenseSet<const VarDecl *> CopiedVars;
784 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000785 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000786 auto IRef = C->varlist_begin();
787 auto ISrcRef = C->source_exprs().begin();
788 auto IDestRef = C->destination_exprs().begin();
789 for (auto *AssignOp : C->assignment_ops()) {
790 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000791 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000792 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000793 // Get the address of the master variable. If we are emitting code with
794 // TLS support, the address is passed from the master as field in the
795 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000796 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000797 if (getLangOpts().OpenMPUseTLS &&
798 getContext().getTargetInfo().isTLSSupported()) {
799 assert(CapturedStmtInfo->lookup(VD) &&
800 "Copyin threadprivates should have been captured!");
801 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
802 VK_LValue, (*IRef)->getExprLoc());
803 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000804 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000805 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000806 MasterAddr =
807 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
808 : CGM.GetAddrOfGlobal(VD),
809 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000810 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000811 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000812 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000813 if (CopiedVars.size() == 1) {
814 // At first check if current thread is a master thread. If it is, no
815 // need to copy data.
816 CopyBegin = createBasicBlock("copyin.not.master");
817 CopyEnd = createBasicBlock("copyin.not.master.end");
818 Builder.CreateCondBr(
819 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000820 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
821 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000822 CopyBegin, CopyEnd);
823 EmitBlock(CopyBegin);
824 }
825 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
826 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000827 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000828 }
829 ++IRef;
830 ++ISrcRef;
831 ++IDestRef;
832 }
833 }
834 if (CopyEnd) {
835 // Exit out of copying procedure for non-master thread.
836 EmitBlock(CopyEnd, /*IsFinished=*/true);
837 return true;
838 }
839 return false;
840}
841
Alexey Bataev38e89532015-04-16 04:54:05 +0000842bool CodeGenFunction::EmitOMPLastprivateClauseInit(
843 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000844 if (!HaveInsertPoint())
845 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000846 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000847 llvm::DenseSet<const VarDecl *> SIMDLCVs;
848 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
849 auto *LoopDirective = cast<OMPLoopDirective>(&D);
850 for (auto *C : LoopDirective->counters()) {
851 SIMDLCVs.insert(
852 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
853 }
854 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000855 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000856 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000857 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000858 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
859 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000860 auto IRef = C->varlist_begin();
861 auto IDestRef = C->destination_exprs().begin();
862 for (auto *IInit : C->private_copies()) {
863 // Keep the address of the original variable for future update at the end
864 // of the loop.
865 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000866 // Taskloops do not require additional initialization, it is done in
867 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000868 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
869 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000870 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000871 DeclRefExpr DRE(
872 const_cast<VarDecl *>(OrigVD),
873 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
874 OrigVD) != nullptr,
875 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
876 return EmitLValue(&DRE).getAddress();
877 });
878 // Check if the variable is also a firstprivate: in this case IInit is
879 // not generated. Initialization of this variable will happen in codegen
880 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000881 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000882 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000883 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
884 // Emit private VarDecl with copy init.
885 EmitDecl(*VD);
886 return GetAddrOfLocalVar(VD);
887 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000888 assert(IsRegistered &&
889 "lastprivate var already registered as private");
890 (void)IsRegistered;
891 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000892 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000893 ++IRef;
894 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000895 }
896 }
897 return HasAtLeastOneLastprivate;
898}
899
900void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000901 const OMPExecutableDirective &D, bool NoFinals,
902 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000903 if (!HaveInsertPoint())
904 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000905 // Emit following code:
906 // if (<IsLastIterCond>) {
907 // orig_var1 = private_orig_var1;
908 // ...
909 // orig_varn = private_orig_varn;
910 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000911 llvm::BasicBlock *ThenBB = nullptr;
912 llvm::BasicBlock *DoneBB = nullptr;
913 if (IsLastIterCond) {
914 ThenBB = createBasicBlock(".omp.lastprivate.then");
915 DoneBB = createBasicBlock(".omp.lastprivate.done");
916 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
917 EmitBlock(ThenBB);
918 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000919 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
920 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000921 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000922 auto IC = LoopDirective->counters().begin();
923 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000924 auto *D =
925 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
926 if (NoFinals)
927 AlreadyEmittedVars.insert(D);
928 else
929 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000930 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000931 }
932 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000933 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
934 auto IRef = C->varlist_begin();
935 auto ISrcRef = C->source_exprs().begin();
936 auto IDestRef = C->destination_exprs().begin();
937 for (auto *AssignOp : C->assignment_ops()) {
938 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
939 QualType Type = PrivateVD->getType();
940 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
941 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
942 // If lastprivate variable is a loop control variable for loop-based
943 // directive, update its value before copyin back to original
944 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000945 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
946 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000947 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
948 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
949 // Get the address of the original variable.
950 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
951 // Get the address of the private variable.
952 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
953 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
954 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000955 Address(Builder.CreateLoad(PrivateAddr),
956 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000957 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000958 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000959 ++IRef;
960 ++ISrcRef;
961 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000962 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000963 if (auto *PostUpdate = C->getPostUpdateExpr())
964 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000965 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000966 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000967 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000968}
969
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000970void CodeGenFunction::EmitOMPReductionClauseInit(
971 const OMPExecutableDirective &D,
972 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000973 if (!HaveInsertPoint())
974 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000975 SmallVector<const Expr *, 4> Shareds;
976 SmallVector<const Expr *, 4> Privates;
977 SmallVector<const Expr *, 4> ReductionOps;
978 SmallVector<const Expr *, 4> LHSs;
979 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000980 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000981 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000982 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 auto ILHS = C->lhs_exprs().begin();
984 auto IRHS = C->rhs_exprs().begin();
985 for (const auto *Ref : C->varlists()) {
986 Shareds.emplace_back(Ref);
987 Privates.emplace_back(*IPriv);
988 ReductionOps.emplace_back(*IRed);
989 LHSs.emplace_back(*ILHS);
990 RHSs.emplace_back(*IRHS);
991 std::advance(IPriv, 1);
992 std::advance(IRed, 1);
993 std::advance(ILHS, 1);
994 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000995 }
996 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
998 unsigned Count = 0;
999 auto ILHS = LHSs.begin();
1000 auto IRHS = RHSs.begin();
1001 auto IPriv = Privates.begin();
1002 for (const auto *IRef : Shareds) {
1003 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1004 // Emit private VarDecl with reduction init.
1005 RedCG.emitSharedLValue(*this, Count);
1006 RedCG.emitAggregateType(*this, Count);
1007 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1008 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1009 RedCG.getSharedLValue(Count),
1010 [&Emission](CodeGenFunction &CGF) {
1011 CGF.EmitAutoVarInit(Emission);
1012 return true;
1013 });
1014 EmitAutoVarCleanups(Emission);
1015 Address BaseAddr = RedCG.adjustPrivateAddress(
1016 *this, Count, Emission.getAllocatedAddress());
1017 bool IsRegistered = PrivateScope.addPrivate(
1018 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1019 assert(IsRegistered && "private var already registered as private");
1020 // Silence the warning about unused variable.
1021 (void)IsRegistered;
1022
1023 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1024 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001025 QualType Type = PrivateVD->getType();
1026 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1027 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001028 // Store the address of the original variable associated with the LHS
1029 // implicit variable.
1030 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1031 return RedCG.getSharedLValue(Count).getAddress();
1032 });
1033 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1034 return GetAddrOfLocalVar(PrivateVD);
1035 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001036 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1037 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001038 // Store the address of the original variable associated with the LHS
1039 // implicit variable.
1040 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1041 return RedCG.getSharedLValue(Count).getAddress();
1042 });
1043 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1044 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1045 ConvertTypeForMem(RHSVD->getType()),
1046 "rhs.begin");
1047 });
1048 } else {
1049 QualType Type = PrivateVD->getType();
1050 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1051 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1052 // Store the address of the original variable associated with the LHS
1053 // implicit variable.
1054 if (IsArray) {
1055 OriginalAddr = Builder.CreateElementBitCast(
1056 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1057 }
1058 PrivateScope.addPrivate(
1059 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1060 PrivateScope.addPrivate(
1061 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1062 return IsArray
1063 ? Builder.CreateElementBitCast(
1064 GetAddrOfLocalVar(PrivateVD),
1065 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1066 : GetAddrOfLocalVar(PrivateVD);
1067 });
1068 }
1069 ++ILHS;
1070 ++IRHS;
1071 ++IPriv;
1072 ++Count;
1073 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001074}
1075
1076void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001077 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001078 if (!HaveInsertPoint())
1079 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001080 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001081 llvm::SmallVector<const Expr *, 8> LHSExprs;
1082 llvm::SmallVector<const Expr *, 8> RHSExprs;
1083 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001084 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001085 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001086 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001087 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001088 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1089 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1090 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1091 }
1092 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001093 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1094 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1095 D.getDirectiveKind() == OMPD_simd;
1096 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001097 // Emit nowait reduction if nowait clause is present or directive is a
1098 // parallel directive (it always has implicit barrier).
1099 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001100 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001101 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001102 }
1103}
1104
Alexey Bataev61205072016-03-02 04:57:40 +00001105static void emitPostUpdateForReductionClause(
1106 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1107 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1108 if (!CGF.HaveInsertPoint())
1109 return;
1110 llvm::BasicBlock *DoneBB = nullptr;
1111 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1112 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1113 if (!DoneBB) {
1114 if (auto *Cond = CondGen(CGF)) {
1115 // If the first post-update expression is found, emit conditional
1116 // block if it was requested.
1117 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1118 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1119 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1120 CGF.EmitBlock(ThenBB);
1121 }
1122 }
1123 CGF.EmitIgnoredExpr(PostUpdate);
1124 }
1125 }
1126 if (DoneBB)
1127 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1128}
1129
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001130namespace {
1131/// Codegen lambda for appending distribute lower and upper bounds to outlined
1132/// parallel function. This is necessary for combined constructs such as
1133/// 'distribute parallel for'
1134typedef llvm::function_ref<void(CodeGenFunction &,
1135 const OMPExecutableDirective &,
1136 llvm::SmallVectorImpl<llvm::Value *> &)>
1137 CodeGenBoundParametersTy;
1138} // anonymous namespace
1139
1140static void emitCommonOMPParallelDirective(
1141 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1142 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1143 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001144 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1145 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1146 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001147 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001148 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001149 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1150 /*IgnoreResultAssign*/ true);
1151 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1152 CGF, NumThreads, NumThreadsClause->getLocStart());
1153 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001154 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001155 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001156 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1157 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1158 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001159 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001160 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1161 if (C->getNameModifier() == OMPD_unknown ||
1162 C->getNameModifier() == OMPD_parallel) {
1163 IfCond = C->getCondition();
1164 break;
1165 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001166 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001167
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001168 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001169 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001170 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1171 // lower and upper bounds with the pragma 'for' chunking mechanism.
1172 // The following lambda takes care of appending the lower and upper bound
1173 // parameters when necessary
1174 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001175 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001176 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001177 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001178}
1179
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001180static void emitEmptyBoundParameters(CodeGenFunction &,
1181 const OMPExecutableDirective &,
1182 llvm::SmallVectorImpl<llvm::Value *> &) {}
1183
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001184void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001185 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001186 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001188 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001189 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1190 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001191 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001192 // propagation master's thread values of threadprivate variables to local
1193 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001194 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1195 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1196 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001197 }
1198 CGF.EmitOMPPrivateClause(S, PrivateScope);
1199 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1200 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001201 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001202 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001203 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001204 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1205 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001206 emitPostUpdateForReductionClause(
1207 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001208}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001209
Alexey Bataev0f34da12015-07-02 04:17:07 +00001210void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1211 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001212 RunCleanupsScope BodyScope(*this);
1213 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001214 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001215 EmitIgnoredExpr(I);
1216 }
Alexander Musman3276a272015-03-21 10:12:56 +00001217 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001218 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001219 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001220 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001221 }
1222
Alexander Musmana5f070a2014-10-01 06:03:56 +00001223 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001224 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001225 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001226 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001227 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001228 // The end (updates/cleanups).
1229 EmitBlock(Continue.getBlock());
1230 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001231}
1232
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001233void CodeGenFunction::EmitOMPInnerLoop(
1234 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1235 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001236 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1237 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001238 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239
1240 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001241 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001242 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001243 const SourceRange &R = S.getSourceRange();
1244 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1245 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246
1247 // If there are any cleanups between here and the loop-exit scope,
1248 // create a block to stage a loop exit along.
1249 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001250 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001251 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001252
Alexander Musmand196ef22014-10-07 08:57:09 +00001253 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001254
Alexey Bataev2df54a02015-03-12 08:53:29 +00001255 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001256 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001257 if (ExitBlock != LoopExit.getBlock()) {
1258 EmitBlock(ExitBlock);
1259 EmitBranchThroughCleanup(LoopExit);
1260 }
1261
1262 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001263 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001264
1265 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001266 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001267 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1268
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001269 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001270
1271 // Emit "IV = IV + 1" and a back-edge to the condition block.
1272 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001273 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001274 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275 BreakContinueStack.pop_back();
1276 EmitBranch(CondBlock);
1277 LoopStack.pop();
1278 // Emit the fall-through block.
1279 EmitBlock(LoopExit.getBlock());
1280}
1281
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001282bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001283 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001284 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001285 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001286 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001287 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001288 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001289 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001290 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001291 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1292 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1293 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1294 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1295 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1296 VD->getInit()->getType(), VK_LValue,
1297 VD->getInit()->getExprLoc());
1298 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1299 VD->getType()),
1300 /*capturedByInit=*/false);
1301 EmitAutoVarCleanups(Emission);
1302 } else
1303 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001304 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001305 // Emit the linear steps for the linear clauses.
1306 // If a step is not constant, it is pre-calculated before the loop.
1307 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1308 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001309 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001310 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001311 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001312 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001313 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001314 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001315}
1316
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001317void CodeGenFunction::EmitOMPLinearClauseFinal(
1318 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001319 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001320 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001321 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001322 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001323 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001324 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001325 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001326 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001327 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001329 // If the first post-update expression is found, emit conditional
1330 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001331 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1332 DoneBB = createBasicBlock(".omp.linear.pu.done");
1333 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1334 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001335 }
1336 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001337 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1338 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001339 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001340 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341 Address OrigAddr = EmitLValue(&DRE).getAddress();
1342 CodeGenFunction::OMPPrivateScope VarScope(*this);
1343 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001344 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001345 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001346 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001347 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001348 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001349 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001350 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001351 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001352 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353}
1354
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001355static void emitAlignedClause(CodeGenFunction &CGF,
1356 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001357 if (!CGF.HaveInsertPoint())
1358 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001359 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001360 unsigned ClauseAlignment = 0;
1361 if (auto AlignmentExpr = Clause->getAlignment()) {
1362 auto AlignmentCI =
1363 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1364 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001365 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001366 for (auto E : Clause->varlists()) {
1367 unsigned Alignment = ClauseAlignment;
1368 if (Alignment == 0) {
1369 // OpenMP [2.8.1, Description]
1370 // If no optional parameter is specified, implementation-defined default
1371 // alignments for SIMD instructions on the target platforms are assumed.
1372 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001373 CGF.getContext()
1374 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1375 E->getType()->getPointeeType()))
1376 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001377 }
1378 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1379 "alignment is not power of 2");
1380 if (Alignment != 0) {
1381 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1382 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1383 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001384 }
1385 }
1386}
1387
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001388void CodeGenFunction::EmitOMPPrivateLoopCounters(
1389 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1390 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001391 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001392 auto I = S.private_counters().begin();
1393 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001394 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1395 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001396 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001397 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398 if (!LocalDeclMap.count(PrivateVD)) {
1399 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1400 EmitAutoVarCleanups(VarEmission);
1401 }
1402 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1403 /*RefersToEnclosingVariableOrCapture=*/false,
1404 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1405 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001406 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001407 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1408 VD->hasGlobalStorage()) {
1409 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1410 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1411 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1412 E->getType(), VK_LValue, E->getExprLoc());
1413 return EmitLValue(&DRE).getAddress();
1414 });
1415 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001416 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001417 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001418}
1419
Alexey Bataev62dbb972015-04-22 11:59:37 +00001420static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1421 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1422 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001423 if (!CGF.HaveInsertPoint())
1424 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001425 {
1426 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001427 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001428 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001429 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001430 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001431 CGF.EmitIgnoredExpr(I);
1432 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001433 }
1434 // Check that loop is executed at least one time.
1435 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1436}
1437
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001438void CodeGenFunction::EmitOMPLinearClause(
1439 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1440 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001441 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001442 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1443 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1444 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1445 for (auto *C : LoopDirective->counters()) {
1446 SIMDLCVs.insert(
1447 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1448 }
1449 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001450 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001451 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001452 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001453 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1454 auto *PrivateVD =
1455 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001456 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1457 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1458 // Emit private VarDecl with copy init.
1459 EmitVarDecl(*PrivateVD);
1460 return GetAddrOfLocalVar(PrivateVD);
1461 });
1462 assert(IsRegistered && "linear var already registered as private");
1463 // Silence the warning about unused variable.
1464 (void)IsRegistered;
1465 } else
1466 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001467 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001468 }
1469 }
1470}
1471
Alexey Bataev45bfad52015-08-21 12:19:04 +00001472static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001473 const OMPExecutableDirective &D,
1474 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001475 if (!CGF.HaveInsertPoint())
1476 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001477 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001478 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1479 /*ignoreResult=*/true);
1480 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1481 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1482 // In presence of finite 'safelen', it may be unsafe to mark all
1483 // the memory instructions parallel, because loop-carried
1484 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001485 if (!IsMonotonic)
1486 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001487 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001488 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1489 /*ignoreResult=*/true);
1490 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001491 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001492 // In presence of finite 'safelen', it may be unsafe to mark all
1493 // the memory instructions parallel, because loop-carried
1494 // dependences of 'safelen' iterations are possible.
1495 CGF.LoopStack.setParallel(false);
1496 }
1497}
1498
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001499void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1500 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001501 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001502 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001503 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001504 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001505}
1506
Alexey Bataevef549a82016-03-09 09:49:09 +00001507void CodeGenFunction::EmitOMPSimdFinal(
1508 const OMPLoopDirective &D,
1509 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001510 if (!HaveInsertPoint())
1511 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001512 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001513 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001514 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001515 for (auto F : D.finals()) {
1516 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001517 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1518 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1519 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1520 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001521 if (!DoneBB) {
1522 if (auto *Cond = CondGen(*this)) {
1523 // If the first post-update expression is found, emit conditional
1524 // block if it was requested.
1525 auto *ThenBB = createBasicBlock(".omp.final.then");
1526 DoneBB = createBasicBlock(".omp.final.done");
1527 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1528 EmitBlock(ThenBB);
1529 }
1530 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001531 Address OrigAddr = Address::invalid();
1532 if (CED)
1533 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1534 else {
1535 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1536 /*RefersToEnclosingVariableOrCapture=*/false,
1537 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1538 OrigAddr = EmitLValue(&DRE).getAddress();
1539 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001540 OMPPrivateScope VarScope(*this);
1541 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001542 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001543 (void)VarScope.Privatize();
1544 EmitIgnoredExpr(F);
1545 }
1546 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001547 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001548 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001549 if (DoneBB)
1550 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001551}
1552
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001553static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1554 const OMPLoopDirective &S,
1555 CodeGenFunction::JumpDest LoopExit) {
1556 CGF.EmitOMPLoopBody(S, LoopExit);
1557 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001558}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001559
Alexey Bataevf8365372017-11-17 17:57:25 +00001560static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1561 PrePostActionTy &Action) {
1562 Action.Enter(CGF);
1563 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1564 "Expected simd directive");
1565 OMPLoopScope PreInitScope(CGF, S);
1566 // if (PreCond) {
1567 // for (IV in 0..LastIteration) BODY;
1568 // <Final counter/linear vars updates>;
1569 // }
1570 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001571
Alexey Bataevf8365372017-11-17 17:57:25 +00001572 // Emit: if (PreCond) - begin.
1573 // If the condition constant folds and can be elided, avoid emitting the
1574 // whole loop.
1575 bool CondConstant;
1576 llvm::BasicBlock *ContBlock = nullptr;
1577 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1578 if (!CondConstant)
1579 return;
1580 } else {
1581 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1582 ContBlock = CGF.createBasicBlock("simd.if.end");
1583 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1584 CGF.getProfileCount(&S));
1585 CGF.EmitBlock(ThenBlock);
1586 CGF.incrementProfileCounter(&S);
1587 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001588
Alexey Bataevf8365372017-11-17 17:57:25 +00001589 // Emit the loop iteration variable.
1590 const Expr *IVExpr = S.getIterationVariable();
1591 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1592 CGF.EmitVarDecl(*IVDecl);
1593 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001594
Alexey Bataevf8365372017-11-17 17:57:25 +00001595 // Emit the iterations count variable.
1596 // If it is not a variable, Sema decided to calculate iterations count on
1597 // each iteration (e.g., it is foldable into a constant).
1598 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1599 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1600 // Emit calculation of the iterations count.
1601 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1602 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001603
Alexey Bataevf8365372017-11-17 17:57:25 +00001604 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001605
Alexey Bataevf8365372017-11-17 17:57:25 +00001606 emitAlignedClause(CGF, S);
1607 (void)CGF.EmitOMPLinearClauseInit(S);
1608 {
1609 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1610 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1611 CGF.EmitOMPLinearClause(S, LoopScope);
1612 CGF.EmitOMPPrivateClause(S, LoopScope);
1613 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1614 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1615 (void)LoopScope.Privatize();
1616 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1617 S.getInc(),
1618 [&S](CodeGenFunction &CGF) {
1619 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1620 CGF.EmitStopPoint(&S);
1621 },
1622 [](CodeGenFunction &) {});
1623 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001624 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001625 // Emit final copy of the lastprivate variables at the end of loops.
1626 if (HasLastprivateClause)
1627 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1628 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1629 emitPostUpdateForReductionClause(
1630 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1631 }
1632 CGF.EmitOMPLinearClauseFinal(
1633 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1634 // Emit: if (PreCond) - end.
1635 if (ContBlock) {
1636 CGF.EmitBranch(ContBlock);
1637 CGF.EmitBlock(ContBlock, true);
1638 }
1639}
1640
1641void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1642 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1643 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001644 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001645 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001646 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001647}
1648
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001649void CodeGenFunction::EmitOMPOuterLoop(
1650 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1651 CodeGenFunction::OMPPrivateScope &LoopScope,
1652 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1653 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1654 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001655 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001656
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001657 const Expr *IVExpr = S.getIterationVariable();
1658 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1659 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1660
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001661 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1662
1663 // Start the loop with a block that tests the condition.
1664 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1665 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001666 const SourceRange &R = S.getSourceRange();
1667 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1668 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001669
1670 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001671 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001672 // UB = min(UB, GlobalUB) or
1673 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1674 // 'distribute parallel for')
1675 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001676 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001677 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001678 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001679 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001680 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001681 BoolCondVal =
1682 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1683 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001684 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001685
1686 // If there are any cleanups between here and the loop-exit scope,
1687 // create a block to stage a loop exit along.
1688 auto ExitBlock = LoopExit.getBlock();
1689 if (LoopScope.requiresCleanups())
1690 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1691
1692 auto LoopBody = createBasicBlock("omp.dispatch.body");
1693 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1694 if (ExitBlock != LoopExit.getBlock()) {
1695 EmitBlock(ExitBlock);
1696 EmitBranchThroughCleanup(LoopExit);
1697 }
1698 EmitBlock(LoopBody);
1699
Alexander Musman92bdaab2015-03-12 13:37:50 +00001700 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1701 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001702 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001703 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001704
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001705 // Create a block for the increment.
1706 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1707 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1708
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001709 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1710 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001711 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1712 LoopStack.setParallel(!IsMonotonic);
1713 else
1714 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001715
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001716 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001717
1718 // when 'distribute' is not combined with a 'for':
1719 // while (idx <= UB) { BODY; ++idx; }
1720 // when 'distribute' is combined with a 'for'
1721 // (e.g. 'distribute parallel for')
1722 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1723 EmitOMPInnerLoop(
1724 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1725 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1726 CodeGenLoop(CGF, S, LoopExit);
1727 },
1728 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1729 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1730 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001731
1732 EmitBlock(Continue.getBlock());
1733 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001734 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001735 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001736 EmitIgnoredExpr(LoopArgs.NextLB);
1737 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001738 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001739
1740 EmitBranch(CondBlock);
1741 LoopStack.pop();
1742 // Emit the fall-through block.
1743 EmitBlock(LoopExit.getBlock());
1744
1745 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001746 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1747 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001748 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1749 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001750 };
1751 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001752}
1753
1754void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001755 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001756 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001757 const OMPLoopArguments &LoopArgs,
1758 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001759 auto &RT = CGM.getOpenMPRuntime();
1760
1761 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001762 const bool DynamicOrOrdered =
1763 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001764
1765 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001766 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001767 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001768 "static non-chunked schedule does not need outer loop");
1769
1770 // Emit outer loop.
1771 //
1772 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1773 // When schedule(dynamic,chunk_size) is specified, the iterations are
1774 // distributed to threads in the team in chunks as the threads request them.
1775 // Each thread executes a chunk of iterations, then requests another chunk,
1776 // until no chunks remain to be distributed. Each chunk contains chunk_size
1777 // iterations, except for the last chunk to be distributed, which may have
1778 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1779 //
1780 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1781 // to threads in the team in chunks as the executing threads request them.
1782 // Each thread executes a chunk of iterations, then requests another chunk,
1783 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1784 // each chunk is proportional to the number of unassigned iterations divided
1785 // by the number of threads in the team, decreasing to 1. For a chunk_size
1786 // with value k (greater than 1), the size of each chunk is determined in the
1787 // same way, with the restriction that the chunks do not contain fewer than k
1788 // iterations (except for the last chunk to be assigned, which may have fewer
1789 // than k iterations).
1790 //
1791 // When schedule(auto) is specified, the decision regarding scheduling is
1792 // delegated to the compiler and/or runtime system. The programmer gives the
1793 // implementation the freedom to choose any possible mapping of iterations to
1794 // threads in the team.
1795 //
1796 // When schedule(runtime) is specified, the decision regarding scheduling is
1797 // deferred until run time, and the schedule and chunk size are taken from the
1798 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1799 // implementation defined
1800 //
1801 // while(__kmpc_dispatch_next(&LB, &UB)) {
1802 // idx = LB;
1803 // while (idx <= UB) { BODY; ++idx;
1804 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1805 // } // inner loop
1806 // }
1807 //
1808 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1809 // When schedule(static, chunk_size) is specified, iterations are divided into
1810 // chunks of size chunk_size, and the chunks are assigned to the threads in
1811 // the team in a round-robin fashion in the order of the thread number.
1812 //
1813 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1814 // while (idx <= UB) { BODY; ++idx; } // inner loop
1815 // LB = LB + ST;
1816 // UB = UB + ST;
1817 // }
1818 //
1819
1820 const Expr *IVExpr = S.getIterationVariable();
1821 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1822 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1823
1824 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001825 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1826 llvm::Value *LBVal = DispatchBounds.first;
1827 llvm::Value *UBVal = DispatchBounds.second;
1828 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1829 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001830 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001831 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001832 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001833 CGOpenMPRuntime::StaticRTInput StaticInit(
1834 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1835 LoopArgs.ST, LoopArgs.Chunk);
1836 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1837 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001838 }
1839
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001840 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1841 const unsigned IVSize,
1842 const bool IVSigned) {
1843 if (Ordered) {
1844 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1845 IVSigned);
1846 }
1847 };
1848
1849 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1850 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1851 OuterLoopArgs.IncExpr = S.getInc();
1852 OuterLoopArgs.Init = S.getInit();
1853 OuterLoopArgs.Cond = S.getCond();
1854 OuterLoopArgs.NextLB = S.getNextLowerBound();
1855 OuterLoopArgs.NextUB = S.getNextUpperBound();
1856 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1857 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001858}
1859
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001860static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1861 const unsigned IVSize, const bool IVSigned) {}
1862
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001863void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001864 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1865 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1866 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001867
1868 auto &RT = CGM.getOpenMPRuntime();
1869
1870 // Emit outer loop.
1871 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1872 // dynamic
1873 //
1874
1875 const Expr *IVExpr = S.getIterationVariable();
1876 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1877 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1878
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001879 CGOpenMPRuntime::StaticRTInput StaticInit(
1880 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1881 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1882 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001883
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001884 // for combined 'distribute' and 'for' the increment expression of distribute
1885 // is store in DistInc. For 'distribute' alone, it is in Inc.
1886 Expr *IncExpr;
1887 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1888 IncExpr = S.getDistInc();
1889 else
1890 IncExpr = S.getInc();
1891
1892 // this routine is shared by 'omp distribute parallel for' and
1893 // 'omp distribute': select the right EUB expression depending on the
1894 // directive
1895 OMPLoopArguments OuterLoopArgs;
1896 OuterLoopArgs.LB = LoopArgs.LB;
1897 OuterLoopArgs.UB = LoopArgs.UB;
1898 OuterLoopArgs.ST = LoopArgs.ST;
1899 OuterLoopArgs.IL = LoopArgs.IL;
1900 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1901 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1902 ? S.getCombinedEnsureUpperBound()
1903 : S.getEnsureUpperBound();
1904 OuterLoopArgs.IncExpr = IncExpr;
1905 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1906 ? S.getCombinedInit()
1907 : S.getInit();
1908 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1909 ? S.getCombinedCond()
1910 : S.getCond();
1911 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1912 ? S.getCombinedNextLowerBound()
1913 : S.getNextLowerBound();
1914 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1915 ? S.getCombinedNextUpperBound()
1916 : S.getNextUpperBound();
1917
1918 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1919 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1920 emitEmptyOrdered);
1921}
1922
1923/// Emit a helper variable and return corresponding lvalue.
1924static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1925 const DeclRefExpr *Helper) {
1926 auto VDecl = cast<VarDecl>(Helper->getDecl());
1927 CGF.EmitVarDecl(*VDecl);
1928 return CGF.EmitLValue(Helper);
1929}
1930
1931static std::pair<LValue, LValue>
1932emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1933 const OMPExecutableDirective &S) {
1934 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1935 LValue LB =
1936 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1937 LValue UB =
1938 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1939
1940 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1941 // parallel for') we need to use the 'distribute'
1942 // chunk lower and upper bounds rather than the whole loop iteration
1943 // space. These are parameters to the outlined function for 'parallel'
1944 // and we copy the bounds of the previous schedule into the
1945 // the current ones.
1946 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1947 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1948 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1949 PrevLBVal = CGF.EmitScalarConversion(
1950 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1951 LS.getIterationVariable()->getType(), SourceLocation());
1952 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1953 PrevUBVal = CGF.EmitScalarConversion(
1954 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1955 LS.getIterationVariable()->getType(), SourceLocation());
1956
1957 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1958 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1959
1960 return {LB, UB};
1961}
1962
1963/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1964/// we need to use the LB and UB expressions generated by the worksharing
1965/// code generation support, whereas in non combined situations we would
1966/// just emit 0 and the LastIteration expression
1967/// This function is necessary due to the difference of the LB and UB
1968/// types for the RT emission routines for 'for_static_init' and
1969/// 'for_dispatch_init'
1970static std::pair<llvm::Value *, llvm::Value *>
1971emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1972 const OMPExecutableDirective &S,
1973 Address LB, Address UB) {
1974 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1975 const Expr *IVExpr = LS.getIterationVariable();
1976 // when implementing a dynamic schedule for a 'for' combined with a
1977 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1978 // is not normalized as each team only executes its own assigned
1979 // distribute chunk
1980 QualType IteratorTy = IVExpr->getType();
1981 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1982 SourceLocation());
1983 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1984 SourceLocation());
1985 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001986}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001987
1988static void emitDistributeParallelForDistributeInnerBoundParams(
1989 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1990 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1991 const auto &Dir = cast<OMPLoopDirective>(S);
1992 LValue LB =
1993 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1994 auto LBCast = CGF.Builder.CreateIntCast(
1995 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1996 CapturedVars.push_back(LBCast);
1997 LValue UB =
1998 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1999
2000 auto UBCast = CGF.Builder.CreateIntCast(
2001 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2002 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002003}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002004
2005static void
2006emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2007 const OMPLoopDirective &S,
2008 CodeGenFunction::JumpDest LoopExit) {
2009 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2010 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002011 bool HasCancel = false;
2012 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2013 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2014 HasCancel = D->hasCancel();
2015 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2016 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002017 else if (const auto *D =
2018 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2019 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002020 }
2021 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2022 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002023 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2024 emitDistributeParallelForInnerBounds,
2025 emitDistributeParallelForDispatchBounds);
2026 };
2027
2028 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002029 CGF, S,
2030 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2031 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002032 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002033}
2034
Carlo Bertolli9925f152016-06-27 14:55:37 +00002035void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2036 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002037 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2038 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2039 S.getDistInc());
2040 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002041 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00002042 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002043}
2044
Kelvin Li4a39add2016-07-05 05:00:15 +00002045void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2046 const OMPDistributeParallelForSimdDirective &S) {
2047 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2048 CGM.getOpenMPRuntime().emitInlinedDirective(
2049 *this, OMPD_distribute_parallel_for_simd,
2050 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2051 OMPLoopScope PreInitScope(CGF, S);
2052 CGF.EmitStmt(
2053 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2054 });
2055}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002056
2057void CodeGenFunction::EmitOMPDistributeSimdDirective(
2058 const OMPDistributeSimdDirective &S) {
2059 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2060 CGM.getOpenMPRuntime().emitInlinedDirective(
2061 *this, OMPD_distribute_simd,
2062 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2063 OMPLoopScope PreInitScope(CGF, S);
2064 CGF.EmitStmt(
2065 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2066 });
2067}
2068
Alexey Bataevf8365372017-11-17 17:57:25 +00002069void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2070 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2071 // Emit SPMD target parallel for region as a standalone region.
2072 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2073 emitOMPSimdRegion(CGF, S, Action);
2074 };
2075 llvm::Function *Fn;
2076 llvm::Constant *Addr;
2077 // Emit target region as a standalone region.
2078 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2079 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2080 assert(Fn && Addr && "Target device function emission failed.");
2081}
2082
Kelvin Li986330c2016-07-20 22:57:10 +00002083void CodeGenFunction::EmitOMPTargetSimdDirective(
2084 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002085 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2086 emitOMPSimdRegion(CGF, S, Action);
2087 };
2088 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002089}
2090
Kelvin Li4e325f72016-10-25 12:50:55 +00002091void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2092 const OMPTeamsDistributeSimdDirective &S) {
2093 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2094 CGM.getOpenMPRuntime().emitInlinedDirective(
2095 *this, OMPD_teams_distribute_simd,
2096 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2097 OMPLoopScope PreInitScope(CGF, S);
2098 CGF.EmitStmt(
2099 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2100 });
2101}
2102
Kelvin Li579e41c2016-11-30 23:51:03 +00002103void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2104 const OMPTeamsDistributeParallelForSimdDirective &S) {
2105 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2106 CGM.getOpenMPRuntime().emitInlinedDirective(
2107 *this, OMPD_teams_distribute_parallel_for_simd,
2108 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2109 OMPLoopScope PreInitScope(CGF, S);
2110 CGF.EmitStmt(
2111 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2112 });
2113}
Kelvin Li4e325f72016-10-25 12:50:55 +00002114
Kelvin Li83c451e2016-12-25 04:52:54 +00002115void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2116 const OMPTargetTeamsDistributeDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002117 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li26fd21a2016-12-28 17:57:07 +00002118 CGM.getOpenMPRuntime().emitInlinedDirective(
2119 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002120 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002121 CGF.EmitStmt(
2122 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002123 });
2124}
2125
Kelvin Li80e8f562016-12-29 22:16:30 +00002126void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2127 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002128 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002129 CGM.getOpenMPRuntime().emitInlinedDirective(
2130 *this, OMPD_target_teams_distribute_parallel_for,
2131 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2132 CGF.EmitStmt(
2133 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2134 });
2135}
2136
Kelvin Li1851df52017-01-03 05:23:48 +00002137void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2138 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002139 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002140 CGM.getOpenMPRuntime().emitInlinedDirective(
2141 *this, OMPD_target_teams_distribute_parallel_for_simd,
2142 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2143 CGF.EmitStmt(
2144 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2145 });
2146}
2147
Kelvin Lida681182017-01-10 18:08:18 +00002148void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2149 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002150 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002151 CGM.getOpenMPRuntime().emitInlinedDirective(
2152 *this, OMPD_target_teams_distribute_simd,
2153 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2154 CGF.EmitStmt(
2155 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2156 });
2157}
2158
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002159namespace {
2160 struct ScheduleKindModifiersTy {
2161 OpenMPScheduleClauseKind Kind;
2162 OpenMPScheduleClauseModifier M1;
2163 OpenMPScheduleClauseModifier M2;
2164 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2165 OpenMPScheduleClauseModifier M1,
2166 OpenMPScheduleClauseModifier M2)
2167 : Kind(Kind), M1(M1), M2(M2) {}
2168 };
2169} // namespace
2170
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002171bool CodeGenFunction::EmitOMPWorksharingLoop(
2172 const OMPLoopDirective &S, Expr *EUB,
2173 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2174 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002175 // Emit the loop iteration variable.
2176 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2177 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2178 EmitVarDecl(*IVDecl);
2179
2180 // Emit the iterations count variable.
2181 // If it is not a variable, Sema decided to calculate iterations count on each
2182 // iteration (e.g., it is foldable into a constant).
2183 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2184 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2185 // Emit calculation of the iterations count.
2186 EmitIgnoredExpr(S.getCalcLastIteration());
2187 }
2188
2189 auto &RT = CGM.getOpenMPRuntime();
2190
Alexey Bataev38e89532015-04-16 04:54:05 +00002191 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002192 // Check pre-condition.
2193 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002194 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002196 // If the condition constant folds and can be elided, avoid emitting the
2197 // whole loop.
2198 bool CondConstant;
2199 llvm::BasicBlock *ContBlock = nullptr;
2200 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2201 if (!CondConstant)
2202 return false;
2203 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002204 auto *ThenBlock = createBasicBlock("omp.precond.then");
2205 ContBlock = createBasicBlock("omp.precond.end");
2206 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002207 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002208 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002209 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002210 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002211
Alexey Bataev8b427062016-05-25 12:36:08 +00002212 bool Ordered = false;
2213 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2214 if (OrderedClause->getNumForLoops())
2215 RT.emitDoacrossInit(*this, S);
2216 else
2217 Ordered = true;
2218 }
2219
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002220 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002221 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002222 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002223 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002224
2225 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2226 LValue LB = Bounds.first;
2227 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002228 LValue ST =
2229 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2230 LValue IL =
2231 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2232
Alexander Musmanc6388682014-12-15 07:07:06 +00002233 // Emit 'then' code.
2234 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002235 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002236 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002237 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002238 // initialization of firstprivate variables and post-update of
2239 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002240 CGM.getOpenMPRuntime().emitBarrierCall(
2241 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2242 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002243 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002244 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002245 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002246 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002247 EmitOMPPrivateLoopCounters(S, LoopScope);
2248 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002249 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002250
2251 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002252 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002253 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002254 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002255 ScheduleKind.Schedule = C->getScheduleKind();
2256 ScheduleKind.M1 = C->getFirstScheduleModifier();
2257 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002258 if (const auto *Ch = C->getChunkSize()) {
2259 Chunk = EmitScalarExpr(Ch);
2260 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2261 S.getIterationVariable()->getType(),
2262 S.getLocStart());
2263 }
2264 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002265 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2266 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002267 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2268 // If the static schedule kind is specified or if the ordered clause is
2269 // specified, and if no monotonic modifier is specified, the effect will
2270 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002271 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002272 /* Chunked */ Chunk != nullptr) &&
2273 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002274 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2275 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002276 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2277 // When no chunk_size is specified, the iteration space is divided into
2278 // chunks that are approximately equal in size, and at most one chunk is
2279 // distributed to each thread. Note that the size of the chunks is
2280 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002281 CGOpenMPRuntime::StaticRTInput StaticInit(
2282 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2283 UB.getAddress(), ST.getAddress());
2284 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2285 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002286 auto LoopExit =
2287 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002288 // UB = min(UB, GlobalUB);
2289 EmitIgnoredExpr(S.getEnsureUpperBound());
2290 // IV = LB;
2291 EmitIgnoredExpr(S.getInit());
2292 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002293 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2294 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002295 [&S, LoopExit](CodeGenFunction &CGF) {
2296 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002297 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002298 },
2299 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002300 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002301 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002302 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002303 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2304 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002305 };
2306 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002307 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002308 const bool IsMonotonic =
2309 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2310 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2311 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2312 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002313 // Emit the outer loop, which requests its work chunk [LB..UB] from
2314 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002315 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2316 ST.getAddress(), IL.getAddress(),
2317 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002318 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002319 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002320 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002321 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2322 EmitOMPSimdFinal(S,
2323 [&](CodeGenFunction &CGF) -> llvm::Value * {
2324 return CGF.Builder.CreateIsNotNull(
2325 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2326 });
2327 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002328 EmitOMPReductionClauseFinal(
2329 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2330 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2331 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002332 // Emit post-update of the reduction variables if IsLastIter != 0.
2333 emitPostUpdateForReductionClause(
2334 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2335 return CGF.Builder.CreateIsNotNull(
2336 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2337 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002338 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2339 if (HasLastprivateClause)
2340 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002341 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2342 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002343 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002344 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002345 return CGF.Builder.CreateIsNotNull(
2346 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2347 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002348 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002349 if (ContBlock) {
2350 EmitBranch(ContBlock);
2351 EmitBlock(ContBlock, true);
2352 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002353 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002354 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002355}
2356
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002357/// The following two functions generate expressions for the loop lower
2358/// and upper bounds in case of static and dynamic (dispatch) schedule
2359/// of the associated 'for' or 'distribute' loop.
2360static std::pair<LValue, LValue>
2361emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2362 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2363 LValue LB =
2364 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2365 LValue UB =
2366 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2367 return {LB, UB};
2368}
2369
2370/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2371/// consider the lower and upper bound expressions generated by the
2372/// worksharing loop support, but we use 0 and the iteration space size as
2373/// constants
2374static std::pair<llvm::Value *, llvm::Value *>
2375emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2376 Address LB, Address UB) {
2377 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2378 const Expr *IVExpr = LS.getIterationVariable();
2379 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2380 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2381 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2382 return {LBVal, UBVal};
2383}
2384
Alexander Musmanc6388682014-12-15 07:07:06 +00002385void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002386 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002387 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2388 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002389 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002390 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2391 emitForLoopBounds,
2392 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002393 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002394 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002395 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002396 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2397 S.hasCancel());
2398 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002399
2400 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002401 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002402 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2403 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002404}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002405
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002406void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002407 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002408 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2409 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002410 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2411 emitForLoopBounds,
2412 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002413 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002414 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002415 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002416 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2417 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002418
2419 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002420 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002421 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2422 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002423}
2424
Alexey Bataev2df54a02015-03-12 08:53:29 +00002425static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2426 const Twine &Name,
2427 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002428 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002429 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002430 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002431 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002432}
2433
Alexey Bataev3392d762016-02-16 11:18:12 +00002434void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002435 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2436 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002437 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002438 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2439 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002440 auto &C = CGF.CGM.getContext();
2441 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2442 // Emit helper vars inits.
2443 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2444 CGF.Builder.getInt32(0));
2445 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2446 : CGF.Builder.getInt32(0);
2447 LValue UB =
2448 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2449 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2450 CGF.Builder.getInt32(1));
2451 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2452 CGF.Builder.getInt32(0));
2453 // Loop counter.
2454 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2455 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2456 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2457 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2458 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2459 // Generate condition for loop.
2460 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002461 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002462 // Increment for loop counter.
2463 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2464 S.getLocStart());
2465 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2466 // Iterate through all sections and emit a switch construct:
2467 // switch (IV) {
2468 // case 0:
2469 // <SectionStmt[0]>;
2470 // break;
2471 // ...
2472 // case <NumSection> - 1:
2473 // <SectionStmt[<NumSection> - 1]>;
2474 // break;
2475 // }
2476 // .omp.sections.exit:
2477 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2478 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2479 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2480 CS == nullptr ? 1 : CS->size());
2481 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002482 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002483 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002484 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2485 CGF.EmitBlock(CaseBB);
2486 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002487 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002488 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002489 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002490 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002491 } else {
2492 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2493 CGF.EmitBlock(CaseBB);
2494 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2495 CGF.EmitStmt(Stmt);
2496 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002497 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002498 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002499 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002500
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002501 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2502 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002503 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002504 // initialization of firstprivate variables and post-update of lastprivate
2505 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002506 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2507 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2508 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002509 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002510 CGF.EmitOMPPrivateClause(S, LoopScope);
2511 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2512 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2513 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002514
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002515 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002516 OpenMPScheduleTy ScheduleKind;
2517 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002518 CGOpenMPRuntime::StaticRTInput StaticInit(
2519 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2520 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002521 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002522 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002523 // UB = min(UB, GlobalUB);
2524 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2525 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2526 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2527 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2528 // IV = LB;
2529 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2530 // while (idx <= UB) { BODY; ++idx; }
2531 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2532 [](CodeGenFunction &) {});
2533 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002534 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002535 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2536 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002537 };
2538 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002539 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002540 // Emit post-update of the reduction variables if IsLastIter != 0.
2541 emitPostUpdateForReductionClause(
2542 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2543 return CGF.Builder.CreateIsNotNull(
2544 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2545 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002546
2547 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2548 if (HasLastprivates)
2549 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002550 S, /*NoFinals=*/false,
2551 CGF.Builder.CreateIsNotNull(
2552 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002553 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002554
2555 bool HasCancel = false;
2556 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2557 HasCancel = OSD->hasCancel();
2558 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2559 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002560 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002561 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2562 HasCancel);
2563 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2564 // clause. Otherwise the barrier will be generated by the codegen for the
2565 // directive.
2566 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002567 // Emit implicit barrier to synchronize threads and avoid data races on
2568 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002569 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2570 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002571 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002572}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002573
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002574void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002575 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002576 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002577 EmitSections(S);
2578 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002579 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002580 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002581 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2582 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002583 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002584}
2585
2586void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002587 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002588 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002589 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002590 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002591 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2592 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002593}
2594
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002595void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002596 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002597 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002598 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002599 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002600 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002601 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002602 // Build a list of copyprivate variables along with helper expressions
2603 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002604 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002605 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002606 DestExprs.append(C->destination_exprs().begin(),
2607 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002608 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002609 AssignmentOps.append(C->assignment_ops().begin(),
2610 C->assignment_ops().end());
2611 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002612 // Emit code for 'single' region along with 'copyprivate' clauses
2613 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2614 Action.Enter(CGF);
2615 OMPPrivateScope SingleScope(CGF);
2616 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2617 CGF.EmitOMPPrivateClause(S, SingleScope);
2618 (void)SingleScope.Privatize();
2619 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2620 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002621 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002622 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002623 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2624 CopyprivateVars, DestExprs,
2625 SrcExprs, AssignmentOps);
2626 }
2627 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2628 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002629 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002630 CGM.getOpenMPRuntime().emitBarrierCall(
2631 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002632 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002633 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002634}
2635
Alexey Bataev8d690652014-12-04 07:23:53 +00002636void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002637 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2638 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002639 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002640 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002641 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002642 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002643}
2644
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002645void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002646 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2647 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002648 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002649 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002650 Expr *Hint = nullptr;
2651 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2652 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002653 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002654 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2655 S.getDirectiveName().getAsString(),
2656 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002657}
2658
Alexey Bataev671605e2015-04-13 05:28:11 +00002659void CodeGenFunction::EmitOMPParallelForDirective(
2660 const OMPParallelForDirective &S) {
2661 // Emit directive as a combined directive that consists of two implicit
2662 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002663 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002664 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002665 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2666 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002667 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002668 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2669 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002670}
2671
Alexander Musmane4e893b2014-09-23 09:33:00 +00002672void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002673 const OMPParallelForSimdDirective &S) {
2674 // Emit directive as a combined directive that consists of two implicit
2675 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002676 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002677 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2678 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002679 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002680 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2681 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002682}
2683
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002684void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002685 const OMPParallelSectionsDirective &S) {
2686 // Emit directive as a combined directive that consists of two implicit
2687 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002688 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2689 CGF.EmitSections(S);
2690 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002691 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2692 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002693}
2694
Alexey Bataev7292c292016-04-25 12:22:29 +00002695void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2696 const RegionCodeGenTy &BodyGen,
2697 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002698 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002699 // Emit outlined function for task construct.
2700 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002701 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002702 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002703 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002704 // Check if the task is final
2705 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2706 // If the condition constant folds and can be elided, try to avoid emitting
2707 // the condition and the dead arm of the if/else.
2708 auto *Cond = Clause->getCondition();
2709 bool CondConstant;
2710 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2711 Data.Final.setInt(CondConstant);
2712 else
2713 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2714 } else {
2715 // By default the task is not final.
2716 Data.Final.setInt(/*IntVal=*/false);
2717 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002718 // Check if the task has 'priority' clause.
2719 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002720 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002721 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002722 Data.Priority.setPointer(EmitScalarConversion(
2723 EmitScalarExpr(Prio), Prio->getType(),
2724 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2725 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002726 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002727 // The first function argument for tasks is a thread id, the second one is a
2728 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002729 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2730 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002731 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002732 auto IRef = C->varlist_begin();
2733 for (auto *IInit : C->private_copies()) {
2734 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2735 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002736 Data.PrivateVars.push_back(*IRef);
2737 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002738 }
2739 ++IRef;
2740 }
2741 }
2742 EmittedAsPrivate.clear();
2743 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002744 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002745 auto IRef = C->varlist_begin();
2746 auto IElemInitRef = C->inits().begin();
2747 for (auto *IInit : C->private_copies()) {
2748 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2749 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002750 Data.FirstprivateVars.push_back(*IRef);
2751 Data.FirstprivateCopies.push_back(IInit);
2752 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002753 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002754 ++IRef;
2755 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002756 }
2757 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002758 // Get list of lastprivate variables (for taskloops).
2759 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2760 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2761 auto IRef = C->varlist_begin();
2762 auto ID = C->destination_exprs().begin();
2763 for (auto *IInit : C->private_copies()) {
2764 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2765 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2766 Data.LastprivateVars.push_back(*IRef);
2767 Data.LastprivateCopies.push_back(IInit);
2768 }
2769 LastprivateDstsOrigs.insert(
2770 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2771 cast<DeclRefExpr>(*IRef)});
2772 ++IRef;
2773 ++ID;
2774 }
2775 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002776 SmallVector<const Expr *, 4> LHSs;
2777 SmallVector<const Expr *, 4> RHSs;
2778 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2779 auto IPriv = C->privates().begin();
2780 auto IRed = C->reduction_ops().begin();
2781 auto ILHS = C->lhs_exprs().begin();
2782 auto IRHS = C->rhs_exprs().begin();
2783 for (const auto *Ref : C->varlists()) {
2784 Data.ReductionVars.emplace_back(Ref);
2785 Data.ReductionCopies.emplace_back(*IPriv);
2786 Data.ReductionOps.emplace_back(*IRed);
2787 LHSs.emplace_back(*ILHS);
2788 RHSs.emplace_back(*IRHS);
2789 std::advance(IPriv, 1);
2790 std::advance(IRed, 1);
2791 std::advance(ILHS, 1);
2792 std::advance(IRHS, 1);
2793 }
2794 }
2795 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2796 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002797 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002798 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2799 for (auto *IRef : C->varlists())
2800 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002801 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002802 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002803 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002804 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002805 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2806 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002807 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002808 auto *CopyFn = CGF.Builder.CreateLoad(
2809 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2810 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2811 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2812 // Map privates.
2813 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2814 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2815 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002816 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002817 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2818 Address PrivatePtr = CGF.CreateMemTemp(
2819 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2820 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2821 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002822 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002823 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002824 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2825 Address PrivatePtr =
2826 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2827 ".firstpriv.ptr.addr");
2828 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2829 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002830 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002831 for (auto *E : Data.LastprivateVars) {
2832 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2833 Address PrivatePtr =
2834 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2835 ".lastpriv.ptr.addr");
2836 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2837 CallArgs.push_back(PrivatePtr.getPointer());
2838 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002839 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2840 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002841 for (auto &&Pair : LastprivateDstsOrigs) {
2842 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2843 DeclRefExpr DRE(
2844 const_cast<VarDecl *>(OrigVD),
2845 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2846 OrigVD) != nullptr,
2847 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2848 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2849 return CGF.EmitLValue(&DRE).getAddress();
2850 });
2851 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002852 for (auto &&Pair : PrivatePtrs) {
2853 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2854 CGF.getContext().getDeclAlign(Pair.first));
2855 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2856 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002857 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002858 if (Data.Reductions) {
2859 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2860 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2861 Data.ReductionOps);
2862 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2863 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2864 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2865 RedCG.emitSharedLValue(CGF, Cnt);
2866 RedCG.emitAggregateType(CGF, Cnt);
2867 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2868 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2869 Replacement =
2870 Address(CGF.EmitScalarConversion(
2871 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2872 CGF.getContext().getPointerType(
2873 Data.ReductionCopies[Cnt]->getType()),
2874 SourceLocation()),
2875 Replacement.getAlignment());
2876 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2877 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2878 [Replacement]() { return Replacement; });
2879 // FIXME: This must removed once the runtime library is fixed.
2880 // Emit required threadprivate variables for
2881 // initilizer/combiner/finalizer.
2882 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2883 RedCG, Cnt);
2884 }
2885 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002886 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002887 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002888 SmallVector<const Expr *, 4> InRedVars;
2889 SmallVector<const Expr *, 4> InRedPrivs;
2890 SmallVector<const Expr *, 4> InRedOps;
2891 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2892 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2893 auto IPriv = C->privates().begin();
2894 auto IRed = C->reduction_ops().begin();
2895 auto ITD = C->taskgroup_descriptors().begin();
2896 for (const auto *Ref : C->varlists()) {
2897 InRedVars.emplace_back(Ref);
2898 InRedPrivs.emplace_back(*IPriv);
2899 InRedOps.emplace_back(*IRed);
2900 TaskgroupDescriptors.emplace_back(*ITD);
2901 std::advance(IPriv, 1);
2902 std::advance(IRed, 1);
2903 std::advance(ITD, 1);
2904 }
2905 }
2906 // Privatize in_reduction items here, because taskgroup descriptors must be
2907 // privatized earlier.
2908 OMPPrivateScope InRedScope(CGF);
2909 if (!InRedVars.empty()) {
2910 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2911 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2912 RedCG.emitSharedLValue(CGF, Cnt);
2913 RedCG.emitAggregateType(CGF, Cnt);
2914 // The taskgroup descriptor variable is always implicit firstprivate and
2915 // privatized already during procoessing of the firstprivates.
2916 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2917 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2918 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2919 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2920 Replacement = Address(
2921 CGF.EmitScalarConversion(
2922 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2923 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2924 SourceLocation()),
2925 Replacement.getAlignment());
2926 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2927 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2928 [Replacement]() { return Replacement; });
2929 // FIXME: This must removed once the runtime library is fixed.
2930 // Emit required threadprivate variables for
2931 // initilizer/combiner/finalizer.
2932 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2933 RedCG, Cnt);
2934 }
2935 }
2936 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002937
2938 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002939 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002940 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002941 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2942 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2943 Data.NumberOfParts);
2944 OMPLexicalScope Scope(*this, S);
2945 TaskGen(*this, OutlinedFn, Data);
2946}
2947
2948void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2949 // Emit outlined function for task construct.
2950 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2951 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002952 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002953 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002954 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2955 if (C->getNameModifier() == OMPD_unknown ||
2956 C->getNameModifier() == OMPD_task) {
2957 IfCond = C->getCondition();
2958 break;
2959 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002960 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002961
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002962 OMPTaskDataTy Data;
2963 // Check if we should emit tied or untied task.
2964 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002965 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2966 CGF.EmitStmt(CS->getCapturedStmt());
2967 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002968 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002969 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002970 const OMPTaskDataTy &Data) {
2971 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2972 SharedsTy, CapturedStruct, IfCond,
2973 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002974 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002975 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002976}
2977
Alexey Bataev9f797f32015-02-05 05:57:51 +00002978void CodeGenFunction::EmitOMPTaskyieldDirective(
2979 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002981}
2982
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002983void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002984 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002985}
2986
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002987void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2988 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002989}
2990
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002991void CodeGenFunction::EmitOMPTaskgroupDirective(
2992 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002993 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2994 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002995 if (const Expr *E = S.getReductionRef()) {
2996 SmallVector<const Expr *, 4> LHSs;
2997 SmallVector<const Expr *, 4> RHSs;
2998 OMPTaskDataTy Data;
2999 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3000 auto IPriv = C->privates().begin();
3001 auto IRed = C->reduction_ops().begin();
3002 auto ILHS = C->lhs_exprs().begin();
3003 auto IRHS = C->rhs_exprs().begin();
3004 for (const auto *Ref : C->varlists()) {
3005 Data.ReductionVars.emplace_back(Ref);
3006 Data.ReductionCopies.emplace_back(*IPriv);
3007 Data.ReductionOps.emplace_back(*IRed);
3008 LHSs.emplace_back(*ILHS);
3009 RHSs.emplace_back(*IRHS);
3010 std::advance(IPriv, 1);
3011 std::advance(IRed, 1);
3012 std::advance(ILHS, 1);
3013 std::advance(IRHS, 1);
3014 }
3015 }
3016 llvm::Value *ReductionDesc =
3017 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3018 LHSs, RHSs, Data);
3019 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3020 CGF.EmitVarDecl(*VD);
3021 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3022 /*Volatile=*/false, E->getType());
3023 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003024 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003025 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003026 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003027 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3028}
3029
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003030void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003031 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003032 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003033 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3034 FlushClause->varlist_end());
3035 }
3036 return llvm::None;
3037 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003038}
3039
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003040void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3041 const CodeGenLoopTy &CodeGenLoop,
3042 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043 // Emit the loop iteration variable.
3044 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3045 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3046 EmitVarDecl(*IVDecl);
3047
3048 // Emit the iterations count variable.
3049 // If it is not a variable, Sema decided to calculate iterations count on each
3050 // iteration (e.g., it is foldable into a constant).
3051 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3052 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3053 // Emit calculation of the iterations count.
3054 EmitIgnoredExpr(S.getCalcLastIteration());
3055 }
3056
3057 auto &RT = CGM.getOpenMPRuntime();
3058
Carlo Bertolli962bb802017-01-03 18:24:42 +00003059 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003060 // Check pre-condition.
3061 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003062 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003063 // Skip the entire loop if we don't meet the precondition.
3064 // If the condition constant folds and can be elided, avoid emitting the
3065 // whole loop.
3066 bool CondConstant;
3067 llvm::BasicBlock *ContBlock = nullptr;
3068 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3069 if (!CondConstant)
3070 return;
3071 } else {
3072 auto *ThenBlock = createBasicBlock("omp.precond.then");
3073 ContBlock = createBasicBlock("omp.precond.end");
3074 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3075 getProfileCount(&S));
3076 EmitBlock(ThenBlock);
3077 incrementProfileCounter(&S);
3078 }
3079
3080 // Emit 'then' code.
3081 {
3082 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003083
3084 LValue LB = EmitOMPHelperVar(
3085 *this, cast<DeclRefExpr>(
3086 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3087 ? S.getCombinedLowerBoundVariable()
3088 : S.getLowerBoundVariable())));
3089 LValue UB = EmitOMPHelperVar(
3090 *this, cast<DeclRefExpr>(
3091 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3092 ? S.getCombinedUpperBoundVariable()
3093 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003094 LValue ST =
3095 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3096 LValue IL =
3097 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3098
3099 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003100 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3101 // Emit implicit barrier to synchronize threads and avoid data races on
3102 // initialization of firstprivate variables and post-update of
3103 // lastprivate variables.
3104 CGM.getOpenMPRuntime().emitBarrierCall(
3105 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3106 /*ForceSimpleCall=*/true);
3107 }
3108 EmitOMPPrivateClause(S, LoopScope);
3109 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003110 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003111 (void)LoopScope.Privatize();
3112
3113 // Detect the distribute schedule kind and chunk.
3114 llvm::Value *Chunk = nullptr;
3115 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3116 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3117 ScheduleKind = C->getDistScheduleKind();
3118 if (const auto *Ch = C->getChunkSize()) {
3119 Chunk = EmitScalarExpr(Ch);
3120 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3121 S.getIterationVariable()->getType(),
3122 S.getLocStart());
3123 }
3124 }
3125 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3126 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3127
3128 // OpenMP [2.10.8, distribute Construct, Description]
3129 // If dist_schedule is specified, kind must be static. If specified,
3130 // iterations are divided into chunks of size chunk_size, chunks are
3131 // assigned to the teams of the league in a round-robin fashion in the
3132 // order of the team number. When no chunk_size is specified, the
3133 // iteration space is divided into chunks that are approximately equal
3134 // in size, and at most one chunk is distributed to each team of the
3135 // league. The size of the chunks is unspecified in this case.
3136 if (RT.isStaticNonchunked(ScheduleKind,
3137 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003138 CGOpenMPRuntime::StaticRTInput StaticInit(
3139 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3140 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003141 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003142 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003143 auto LoopExit =
3144 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3145 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003146 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3147 ? S.getCombinedEnsureUpperBound()
3148 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003150 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3151 ? S.getCombinedInit()
3152 : S.getInit());
3153
3154 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3155 ? S.getCombinedCond()
3156 : S.getCond();
3157
3158 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003159 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003160 // when combined with 'for' (e.g. as in 'distribute parallel for')
3161 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3162 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3163 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3164 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003165 },
3166 [](CodeGenFunction &) {});
3167 EmitBlock(LoopExit.getBlock());
3168 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003169 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003170 } else {
3171 // Emit the outer loop, which requests its work chunk [LB..UB] from
3172 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003173 const OMPLoopArguments LoopArguments = {
3174 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3175 Chunk};
3176 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3177 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003178 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003179
3180 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3181 if (HasLastprivateClause)
3182 EmitOMPLastprivateClauseFinal(
3183 S, /*NoFinals=*/false,
3184 Builder.CreateIsNotNull(
3185 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003186 }
3187
3188 // We're now done with the loop, so jump to the continuation block.
3189 if (ContBlock) {
3190 EmitBranch(ContBlock);
3191 EmitBlock(ContBlock, true);
3192 }
3193 }
3194}
3195
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003196void CodeGenFunction::EmitOMPDistributeDirective(
3197 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003198 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003199
3200 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003201 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003202 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003203 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003204}
3205
Alexey Bataev5f600d62015-09-29 03:48:57 +00003206static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3207 const CapturedStmt *S) {
3208 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3209 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3210 CGF.CapturedStmtInfo = &CapStmtInfo;
3211 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3212 Fn->addFnAttr(llvm::Attribute::NoInline);
3213 return Fn;
3214}
3215
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003216void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003217 if (!S.getAssociatedStmt()) {
3218 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3219 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003220 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003221 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003222 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003223 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3224 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003225 if (C) {
3226 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3227 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3228 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3229 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003230 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3231 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003232 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003233 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003234 CGF.EmitStmt(
3235 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3236 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003237 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003238 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003239 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003240}
3241
Alexey Bataevb57056f2015-01-22 06:17:56 +00003242static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003243 QualType SrcType, QualType DestType,
3244 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003245 assert(CGF.hasScalarEvaluationKind(DestType) &&
3246 "DestType must have scalar evaluation kind.");
3247 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3248 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003249 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3250 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003251 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003252 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003253}
3254
3255static CodeGenFunction::ComplexPairTy
3256convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003257 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003258 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3259 "DestType must have complex evaluation kind.");
3260 CodeGenFunction::ComplexPairTy ComplexVal;
3261 if (Val.isScalar()) {
3262 // Convert the input element to the element type of the complex.
3263 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003264 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3265 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003266 ComplexVal = CodeGenFunction::ComplexPairTy(
3267 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3268 } else {
3269 assert(Val.isComplex() && "Must be a scalar or complex.");
3270 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3271 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3272 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003273 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003274 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003275 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003276 }
3277 return ComplexVal;
3278}
3279
Alexey Bataev5e018f92015-04-23 06:35:10 +00003280static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3281 LValue LVal, RValue RVal) {
3282 if (LVal.isGlobalReg()) {
3283 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3284 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003285 CGF.EmitAtomicStore(RVal, LVal,
3286 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3287 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003288 LVal.isVolatile(), /*IsInit=*/false);
3289 }
3290}
3291
Alexey Bataev8524d152016-01-21 12:35:58 +00003292void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3293 QualType RValTy, SourceLocation Loc) {
3294 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003295 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003296 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3297 *this, RVal, RValTy, LVal.getType(), Loc)),
3298 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003299 break;
3300 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003301 EmitStoreOfComplex(
3302 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003303 /*isInit=*/false);
3304 break;
3305 case TEK_Aggregate:
3306 llvm_unreachable("Must be a scalar or complex.");
3307 }
3308}
3309
Alexey Bataevb57056f2015-01-22 06:17:56 +00003310static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3311 const Expr *X, const Expr *V,
3312 SourceLocation Loc) {
3313 // v = x;
3314 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3315 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3316 LValue XLValue = CGF.EmitLValue(X);
3317 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003318 RValue Res = XLValue.isGlobalReg()
3319 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003320 : CGF.EmitAtomicLoad(
3321 XLValue, Loc,
3322 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3323 : llvm::AtomicOrdering::Monotonic,
3324 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +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)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003330 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003331 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003332}
3333
Alexey Bataevb8329262015-02-27 06:33:30 +00003334static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3335 const Expr *X, const Expr *E,
3336 SourceLocation Loc) {
3337 // x = expr;
3338 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003339 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003340 // OpenMP, 2.12.6, atomic Construct
3341 // Any atomic construct with a seq_cst clause forces the atomically
3342 // performed operation to include an implicit flush operation without a
3343 // list.
3344 if (IsSeqCst)
3345 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3346}
3347
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003348static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3349 RValue Update,
3350 BinaryOperatorKind BO,
3351 llvm::AtomicOrdering AO,
3352 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003353 auto &Context = CGF.CGM.getContext();
3354 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003355 // expression is simple and atomic is allowed for the given type for the
3356 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003357 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003358 !Update.getScalarVal()->getType()->isIntegerTy() ||
3359 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3360 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003361 X.getAddress().getElementType())) ||
3362 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003363 !Context.getTargetInfo().hasBuiltinAtomic(
3364 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003365 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003366
3367 llvm::AtomicRMWInst::BinOp RMWOp;
3368 switch (BO) {
3369 case BO_Add:
3370 RMWOp = llvm::AtomicRMWInst::Add;
3371 break;
3372 case BO_Sub:
3373 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003374 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003375 RMWOp = llvm::AtomicRMWInst::Sub;
3376 break;
3377 case BO_And:
3378 RMWOp = llvm::AtomicRMWInst::And;
3379 break;
3380 case BO_Or:
3381 RMWOp = llvm::AtomicRMWInst::Or;
3382 break;
3383 case BO_Xor:
3384 RMWOp = llvm::AtomicRMWInst::Xor;
3385 break;
3386 case BO_LT:
3387 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3388 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3389 : llvm::AtomicRMWInst::Max)
3390 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3391 : llvm::AtomicRMWInst::UMax);
3392 break;
3393 case BO_GT:
3394 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3395 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3396 : llvm::AtomicRMWInst::Min)
3397 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3398 : llvm::AtomicRMWInst::UMin);
3399 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003400 case BO_Assign:
3401 RMWOp = llvm::AtomicRMWInst::Xchg;
3402 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003403 case BO_Mul:
3404 case BO_Div:
3405 case BO_Rem:
3406 case BO_Shl:
3407 case BO_Shr:
3408 case BO_LAnd:
3409 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003410 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003411 case BO_PtrMemD:
3412 case BO_PtrMemI:
3413 case BO_LE:
3414 case BO_GE:
3415 case BO_EQ:
3416 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003417 case BO_AddAssign:
3418 case BO_SubAssign:
3419 case BO_AndAssign:
3420 case BO_OrAssign:
3421 case BO_XorAssign:
3422 case BO_MulAssign:
3423 case BO_DivAssign:
3424 case BO_RemAssign:
3425 case BO_ShlAssign:
3426 case BO_ShrAssign:
3427 case BO_Comma:
3428 llvm_unreachable("Unsupported atomic update operation");
3429 }
3430 auto *UpdateVal = Update.getScalarVal();
3431 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3432 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003433 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003434 X.getType()->hasSignedIntegerRepresentation());
3435 }
John McCall7f416cc2015-09-08 08:05:57 +00003436 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003437 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003438}
3439
Alexey Bataev5e018f92015-04-23 06:35:10 +00003440std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003441 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3442 llvm::AtomicOrdering AO, SourceLocation Loc,
3443 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3444 // Update expressions are allowed to have the following forms:
3445 // x binop= expr; -> xrval + expr;
3446 // x++, ++x -> xrval + 1;
3447 // x--, --x -> xrval - 1;
3448 // x = x binop expr; -> xrval binop expr
3449 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003450 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3451 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003452 if (X.isGlobalReg()) {
3453 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3454 // 'xrval'.
3455 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3456 } else {
3457 // Perform compare-and-swap procedure.
3458 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003459 }
3460 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003461 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003462}
3463
3464static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3465 const Expr *X, const Expr *E,
3466 const Expr *UE, bool IsXLHSInRHSPart,
3467 SourceLocation Loc) {
3468 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3469 "Update expr in 'atomic update' must be a binary operator.");
3470 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3471 // Update expressions are allowed to have the following forms:
3472 // x binop= expr; -> xrval + expr;
3473 // x++, ++x -> xrval + 1;
3474 // x--, --x -> xrval - 1;
3475 // x = x binop expr; -> xrval binop expr
3476 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003477 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003478 LValue XLValue = CGF.EmitLValue(X);
3479 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003480 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3481 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003482 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3483 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3484 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3485 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3486 auto Gen =
3487 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3488 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3489 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3490 return CGF.EmitAnyExpr(UE);
3491 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003492 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3493 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3494 // OpenMP, 2.12.6, atomic Construct
3495 // Any atomic construct with a seq_cst clause forces the atomically
3496 // performed operation to include an implicit flush operation without a
3497 // list.
3498 if (IsSeqCst)
3499 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3500}
3501
3502static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003503 QualType SourceType, QualType ResType,
3504 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003505 switch (CGF.getEvaluationKind(ResType)) {
3506 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003507 return RValue::get(
3508 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003509 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003510 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003511 return RValue::getComplex(Res.first, Res.second);
3512 }
3513 case TEK_Aggregate:
3514 break;
3515 }
3516 llvm_unreachable("Must be a scalar or complex.");
3517}
3518
3519static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3520 bool IsPostfixUpdate, const Expr *V,
3521 const Expr *X, const Expr *E,
3522 const Expr *UE, bool IsXLHSInRHSPart,
3523 SourceLocation Loc) {
3524 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3525 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3526 RValue NewVVal;
3527 LValue VLValue = CGF.EmitLValue(V);
3528 LValue XLValue = CGF.EmitLValue(X);
3529 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003530 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3531 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003532 QualType NewVValType;
3533 if (UE) {
3534 // 'x' is updated with some additional value.
3535 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3536 "Update expr in 'atomic capture' must be a binary operator.");
3537 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3538 // Update expressions are allowed to have the following forms:
3539 // x binop= expr; -> xrval + expr;
3540 // x++, ++x -> xrval + 1;
3541 // x--, --x -> xrval - 1;
3542 // x = x binop expr; -> xrval binop expr
3543 // x = expr Op x; - > expr binop xrval;
3544 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3545 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3546 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3547 NewVValType = XRValExpr->getType();
3548 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3549 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003550 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003551 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3552 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3553 RValue Res = CGF.EmitAnyExpr(UE);
3554 NewVVal = IsPostfixUpdate ? XRValue : Res;
3555 return Res;
3556 };
3557 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3558 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3559 if (Res.first) {
3560 // 'atomicrmw' instruction was generated.
3561 if (IsPostfixUpdate) {
3562 // Use old value from 'atomicrmw'.
3563 NewVVal = Res.second;
3564 } else {
3565 // 'atomicrmw' does not provide new value, so evaluate it using old
3566 // value of 'x'.
3567 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3568 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3569 NewVVal = CGF.EmitAnyExpr(UE);
3570 }
3571 }
3572 } else {
3573 // 'x' is simply rewritten with some 'expr'.
3574 NewVValType = X->getType().getNonReferenceType();
3575 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003576 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003577 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003578 NewVVal = XRValue;
3579 return ExprRValue;
3580 };
3581 // Try to perform atomicrmw xchg, otherwise simple exchange.
3582 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3583 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3584 Loc, Gen);
3585 if (Res.first) {
3586 // 'atomicrmw' instruction was generated.
3587 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3588 }
3589 }
3590 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003591 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003592 // OpenMP, 2.12.6, atomic Construct
3593 // Any atomic construct with a seq_cst clause forces the atomically
3594 // performed operation to include an implicit flush operation without a
3595 // list.
3596 if (IsSeqCst)
3597 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3598}
3599
Alexey Bataevb57056f2015-01-22 06:17:56 +00003600static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003601 bool IsSeqCst, bool IsPostfixUpdate,
3602 const Expr *X, const Expr *V, const Expr *E,
3603 const Expr *UE, bool IsXLHSInRHSPart,
3604 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003605 switch (Kind) {
3606 case OMPC_read:
3607 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3608 break;
3609 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003610 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3611 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003612 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003613 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003614 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3615 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003616 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003617 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3618 IsXLHSInRHSPart, Loc);
3619 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003620 case OMPC_if:
3621 case OMPC_final:
3622 case OMPC_num_threads:
3623 case OMPC_private:
3624 case OMPC_firstprivate:
3625 case OMPC_lastprivate:
3626 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003627 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003628 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003629 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003630 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003631 case OMPC_collapse:
3632 case OMPC_default:
3633 case OMPC_seq_cst:
3634 case OMPC_shared:
3635 case OMPC_linear:
3636 case OMPC_aligned:
3637 case OMPC_copyin:
3638 case OMPC_copyprivate:
3639 case OMPC_flush:
3640 case OMPC_proc_bind:
3641 case OMPC_schedule:
3642 case OMPC_ordered:
3643 case OMPC_nowait:
3644 case OMPC_untied:
3645 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003646 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003647 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003648 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003649 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003650 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003651 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003652 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003653 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003654 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003655 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003656 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003657 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003658 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003659 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003660 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003661 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003662 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003663 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003664 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003665 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003666 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3667 }
3668}
3669
3670void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003671 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003672 OpenMPClauseKind Kind = OMPC_unknown;
3673 for (auto *C : S.clauses()) {
3674 // Find first clause (skip seq_cst clause, if it is first).
3675 if (C->getClauseKind() != OMPC_seq_cst) {
3676 Kind = C->getClauseKind();
3677 break;
3678 }
3679 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003680
3681 const auto *CS =
3682 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003683 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003684 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003685 }
3686 // Processing for statements under 'atomic capture'.
3687 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3688 for (const auto *C : Compound->body()) {
3689 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3690 enterFullExpression(EWC);
3691 }
3692 }
3693 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003694
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003695 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3696 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003697 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003698 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3699 S.getV(), S.getExpr(), S.getUpdateExpr(),
3700 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003701 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003702 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003703 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003704}
3705
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003706static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3707 const OMPExecutableDirective &S,
3708 const RegionCodeGenTy &CodeGen) {
3709 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3710 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003711 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003712
Samuel Antaoee8fb302016-01-06 13:42:12 +00003713 llvm::Function *Fn = nullptr;
3714 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003715
Samuel Antaobed3c462015-10-02 16:14:20 +00003716 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003717 // Check for the at most one if clause associated with the target region.
3718 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3719 if (C->getNameModifier() == OMPD_unknown ||
3720 C->getNameModifier() == OMPD_target) {
3721 IfCond = C->getCondition();
3722 break;
3723 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003724 }
3725
3726 // Check if we have any device clause associated with the directive.
3727 const Expr *Device = nullptr;
3728 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3729 Device = C->getDevice();
3730 }
3731
Samuel Antaoee8fb302016-01-06 13:42:12 +00003732 // Check if we have an if clause whose conditional always evaluates to false
3733 // or if we do not have any targets specified. If so the target region is not
3734 // an offload entry point.
3735 bool IsOffloadEntry = true;
3736 if (IfCond) {
3737 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003738 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739 IsOffloadEntry = false;
3740 }
3741 if (CGM.getLangOpts().OMPTargetTriples.empty())
3742 IsOffloadEntry = false;
3743
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003744 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003745 StringRef ParentName;
3746 // In case we have Ctors/Dtors we use the complete type variant to produce
3747 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003748 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003750 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3752 else
3753 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003754 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003756 // Emit target region as a standalone region.
3757 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3758 IsOffloadEntry, CodeGen);
3759 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003760 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3761 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003762 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003763 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003764}
3765
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003766static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3767 PrePostActionTy &Action) {
3768 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3769 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3770 CGF.EmitOMPPrivateClause(S, PrivateScope);
3771 (void)PrivateScope.Privatize();
3772
3773 Action.Enter(CGF);
3774 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3775}
3776
3777void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3778 StringRef ParentName,
3779 const OMPTargetDirective &S) {
3780 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3781 emitTargetRegion(CGF, S, Action);
3782 };
3783 llvm::Function *Fn;
3784 llvm::Constant *Addr;
3785 // Emit target region as a standalone region.
3786 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3787 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3788 assert(Fn && Addr && "Target device function emission failed.");
3789}
3790
3791void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3792 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3793 emitTargetRegion(CGF, S, Action);
3794 };
3795 emitCommonOMPTargetDirective(*this, S, CodeGen);
3796}
3797
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003798static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3799 const OMPExecutableDirective &S,
3800 OpenMPDirectiveKind InnermostKind,
3801 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003802 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3803 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3804 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003805
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003806 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3807 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003808 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003809 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3810 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003811
Carlo Bertollic6872252016-04-04 15:55:02 +00003812 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3813 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003814 }
3815
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003816 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003817 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3818 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003819 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3820 CapturedVars);
3821}
3822
3823void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003824 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003825 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003826 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003827 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3828 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003829 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003830 (void)PrivateScope.Privatize();
3831 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003832 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003833 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003834 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003835 emitPostUpdateForReductionClause(
3836 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003837}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003838
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003839static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3840 const OMPTargetTeamsDirective &S) {
3841 auto *CS = S.getCapturedStmt(OMPD_teams);
3842 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003843 // Emit teams region as a standalone region.
3844 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3845 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3846 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3847 CGF.EmitOMPPrivateClause(S, PrivateScope);
3848 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3849 (void)PrivateScope.Privatize();
3850 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003851 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003852 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003853 };
3854 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003855 emitPostUpdateForReductionClause(
3856 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003857}
3858
3859void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3860 CodeGenModule &CGM, StringRef ParentName,
3861 const OMPTargetTeamsDirective &S) {
3862 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3863 emitTargetTeamsRegion(CGF, Action, S);
3864 };
3865 llvm::Function *Fn;
3866 llvm::Constant *Addr;
3867 // Emit target region as a standalone region.
3868 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3869 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3870 assert(Fn && Addr && "Target device function emission failed.");
3871}
3872
3873void CodeGenFunction::EmitOMPTargetTeamsDirective(
3874 const OMPTargetTeamsDirective &S) {
3875 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3876 emitTargetTeamsRegion(CGF, Action, S);
3877 };
3878 emitCommonOMPTargetDirective(*this, S, CodeGen);
3879}
3880
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003881void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3882 const OMPTeamsDistributeDirective &S) {
3883
3884 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3885 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3886 };
3887
3888 // Emit teams region as a standalone region.
3889 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3890 PrePostActionTy &) {
3891 OMPPrivateScope PrivateScope(CGF);
3892 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3893 (void)PrivateScope.Privatize();
3894 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3895 CodeGenDistribute);
3896 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3897 };
3898 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
3899 emitPostUpdateForReductionClause(*this, S,
3900 [](CodeGenFunction &) { return nullptr; });
3901}
3902
Carlo Bertolli62fae152017-11-20 20:46:39 +00003903void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
3904 const OMPTeamsDistributeParallelForDirective &S) {
3905 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3906 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3907 S.getDistInc());
3908 };
3909
3910 // Emit teams region as a standalone region.
3911 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3912 PrePostActionTy &) {
3913 OMPPrivateScope PrivateScope(CGF);
3914 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3915 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00003916 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3917 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003918 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3919 };
3920 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3921 emitPostUpdateForReductionClause(*this, S,
3922 [](CodeGenFunction &) { return nullptr; });
3923}
3924
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003925void CodeGenFunction::EmitOMPCancellationPointDirective(
3926 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003927 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3928 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003929}
3930
Alexey Bataev80909872015-07-02 11:25:17 +00003931void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003932 const Expr *IfCond = nullptr;
3933 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3934 if (C->getNameModifier() == OMPD_unknown ||
3935 C->getNameModifier() == OMPD_cancel) {
3936 IfCond = C->getCondition();
3937 break;
3938 }
3939 }
3940 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003941 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003942}
3943
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003944CodeGenFunction::JumpDest
3945CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003946 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3947 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003948 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003949 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003950 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3951 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003952 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003953 Kind == OMPD_teams_distribute_parallel_for ||
3954 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00003955 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003956}
Michael Wong65f367f2015-07-21 13:44:28 +00003957
Samuel Antaocc10b852016-07-28 14:23:26 +00003958void CodeGenFunction::EmitOMPUseDevicePtrClause(
3959 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3960 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3961 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3962 auto OrigVarIt = C.varlist_begin();
3963 auto InitIt = C.inits().begin();
3964 for (auto PvtVarIt : C.private_copies()) {
3965 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3966 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3967 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3968
3969 // In order to identify the right initializer we need to match the
3970 // declaration used by the mapping logic. In some cases we may get
3971 // OMPCapturedExprDecl that refers to the original declaration.
3972 const ValueDecl *MatchingVD = OrigVD;
3973 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3974 // OMPCapturedExprDecl are used to privative fields of the current
3975 // structure.
3976 auto *ME = cast<MemberExpr>(OED->getInit());
3977 assert(isa<CXXThisExpr>(ME->getBase()) &&
3978 "Base should be the current struct!");
3979 MatchingVD = ME->getMemberDecl();
3980 }
3981
3982 // If we don't have information about the current list item, move on to
3983 // the next one.
3984 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3985 if (InitAddrIt == CaptureDeviceAddrMap.end())
3986 continue;
3987
3988 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3989 // Initialize the temporary initialization variable with the address we
3990 // get from the runtime library. We have to cast the source address
3991 // because it is always a void *. References are materialized in the
3992 // privatization scope, so the initialization here disregards the fact
3993 // the original variable is a reference.
3994 QualType AddrQTy =
3995 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3996 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3997 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3998 setAddrOfLocalVar(InitVD, InitAddr);
3999
4000 // Emit private declaration, it will be initialized by the value we
4001 // declaration we just added to the local declarations map.
4002 EmitDecl(*PvtVD);
4003
4004 // The initialization variables reached its purpose in the emission
4005 // ofthe previous declaration, so we don't need it anymore.
4006 LocalDeclMap.erase(InitVD);
4007
4008 // Return the address of the private variable.
4009 return GetAddrOfLocalVar(PvtVD);
4010 });
4011 assert(IsRegistered && "firstprivate var already registered as private");
4012 // Silence the warning about unused variable.
4013 (void)IsRegistered;
4014
4015 ++OrigVarIt;
4016 ++InitIt;
4017 }
4018}
4019
Michael Wong65f367f2015-07-21 13:44:28 +00004020// Generate the instructions for '#pragma omp target data' directive.
4021void CodeGenFunction::EmitOMPTargetDataDirective(
4022 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004023 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4024
4025 // Create a pre/post action to signal the privatization of the device pointer.
4026 // This action can be replaced by the OpenMP runtime code generation to
4027 // deactivate privatization.
4028 bool PrivatizeDevicePointers = false;
4029 class DevicePointerPrivActionTy : public PrePostActionTy {
4030 bool &PrivatizeDevicePointers;
4031
4032 public:
4033 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4034 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4035 void Enter(CodeGenFunction &CGF) override {
4036 PrivatizeDevicePointers = true;
4037 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004038 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004039 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4040
4041 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4042 CodeGenFunction &CGF, PrePostActionTy &Action) {
4043 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4044 CGF.EmitStmt(
4045 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4046 };
4047
4048 // Codegen that selects wheather to generate the privatization code or not.
4049 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4050 &InnermostCodeGen](CodeGenFunction &CGF,
4051 PrePostActionTy &Action) {
4052 RegionCodeGenTy RCG(InnermostCodeGen);
4053 PrivatizeDevicePointers = false;
4054
4055 // Call the pre-action to change the status of PrivatizeDevicePointers if
4056 // needed.
4057 Action.Enter(CGF);
4058
4059 if (PrivatizeDevicePointers) {
4060 OMPPrivateScope PrivateScope(CGF);
4061 // Emit all instances of the use_device_ptr clause.
4062 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4063 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4064 Info.CaptureDeviceAddrMap);
4065 (void)PrivateScope.Privatize();
4066 RCG(CGF);
4067 } else
4068 RCG(CGF);
4069 };
4070
4071 // Forward the provided action to the privatization codegen.
4072 RegionCodeGenTy PrivRCG(PrivCodeGen);
4073 PrivRCG.setAction(Action);
4074
4075 // Notwithstanding the body of the region is emitted as inlined directive,
4076 // we don't use an inline scope as changes in the references inside the
4077 // region are expected to be visible outside, so we do not privative them.
4078 OMPLexicalScope Scope(CGF, S);
4079 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4080 PrivRCG);
4081 };
4082
4083 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004084
4085 // If we don't have target devices, don't bother emitting the data mapping
4086 // code.
4087 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004088 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004089 return;
4090 }
4091
4092 // Check if we have any if clause associated with the directive.
4093 const Expr *IfCond = nullptr;
4094 if (auto *C = S.getSingleClause<OMPIfClause>())
4095 IfCond = C->getCondition();
4096
4097 // Check if we have any device clause associated with the directive.
4098 const Expr *Device = nullptr;
4099 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4100 Device = C->getDevice();
4101
Samuel Antaocc10b852016-07-28 14:23:26 +00004102 // Set the action to signal privatization of device pointers.
4103 RCG.setAction(PrivAction);
4104
4105 // Emit region code.
4106 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4107 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004108}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004109
Samuel Antaodf67fc42016-01-19 19:15:56 +00004110void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4111 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004112 // If we don't have target devices, don't bother emitting the data mapping
4113 // code.
4114 if (CGM.getLangOpts().OMPTargetTriples.empty())
4115 return;
4116
4117 // Check if we have any if clause associated with the directive.
4118 const Expr *IfCond = nullptr;
4119 if (auto *C = S.getSingleClause<OMPIfClause>())
4120 IfCond = C->getCondition();
4121
4122 // Check if we have any device clause associated with the directive.
4123 const Expr *Device = nullptr;
4124 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4125 Device = C->getDevice();
4126
Alexey Bataev7828b252017-11-21 17:08:48 +00004127 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4128 PrePostActionTy &) {
4129 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4130 Device);
4131 };
4132 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4133 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_enter_data,
4134 CodeGen);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004135}
4136
Samuel Antao72590762016-01-19 20:04:50 +00004137void CodeGenFunction::EmitOMPTargetExitDataDirective(
4138 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004139 // If we don't have target devices, don't bother emitting the data mapping
4140 // code.
4141 if (CGM.getLangOpts().OMPTargetTriples.empty())
4142 return;
4143
4144 // Check if we have any if clause associated with the directive.
4145 const Expr *IfCond = nullptr;
4146 if (auto *C = S.getSingleClause<OMPIfClause>())
4147 IfCond = C->getCondition();
4148
4149 // Check if we have any device clause associated with the directive.
4150 const Expr *Device = nullptr;
4151 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4152 Device = C->getDevice();
4153
Alexey Bataev7828b252017-11-21 17:08:48 +00004154 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4155 PrePostActionTy &) {
4156 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4157 Device);
4158 };
4159 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4160 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_exit_data,
4161 CodeGen);
Samuel Antao72590762016-01-19 20:04:50 +00004162}
4163
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004164static void emitTargetParallelRegion(CodeGenFunction &CGF,
4165 const OMPTargetParallelDirective &S,
4166 PrePostActionTy &Action) {
4167 // Get the captured statement associated with the 'parallel' region.
4168 auto *CS = S.getCapturedStmt(OMPD_parallel);
4169 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004170 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4171 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4172 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4173 CGF.EmitOMPPrivateClause(S, PrivateScope);
4174 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4175 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004176 // TODO: Add support for clauses.
4177 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004178 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004179 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004180 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4181 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004182 emitPostUpdateForReductionClause(
4183 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004184}
4185
4186void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4187 CodeGenModule &CGM, StringRef ParentName,
4188 const OMPTargetParallelDirective &S) {
4189 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4190 emitTargetParallelRegion(CGF, S, Action);
4191 };
4192 llvm::Function *Fn;
4193 llvm::Constant *Addr;
4194 // Emit target region as a standalone region.
4195 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4196 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4197 assert(Fn && Addr && "Target device function emission failed.");
4198}
4199
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004200void CodeGenFunction::EmitOMPTargetParallelDirective(
4201 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004202 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4203 emitTargetParallelRegion(CGF, S, Action);
4204 };
4205 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004206}
4207
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004208static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4209 const OMPTargetParallelForDirective &S,
4210 PrePostActionTy &Action) {
4211 Action.Enter(CGF);
4212 // Emit directive as a combined directive that consists of two implicit
4213 // directives: 'parallel' with 'for' directive.
4214 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004215 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4216 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004217 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4218 emitDispatchForLoopBounds);
4219 };
4220 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4221 emitEmptyBoundParameters);
4222}
4223
4224void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4225 CodeGenModule &CGM, StringRef ParentName,
4226 const OMPTargetParallelForDirective &S) {
4227 // Emit SPMD target parallel for region as a standalone region.
4228 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4229 emitTargetParallelForRegion(CGF, S, Action);
4230 };
4231 llvm::Function *Fn;
4232 llvm::Constant *Addr;
4233 // Emit target region as a standalone region.
4234 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4235 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4236 assert(Fn && Addr && "Target device function emission failed.");
4237}
4238
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004239void CodeGenFunction::EmitOMPTargetParallelForDirective(
4240 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004241 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4242 emitTargetParallelForRegion(CGF, S, Action);
4243 };
4244 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004245}
4246
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004247static void
4248emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4249 const OMPTargetParallelForSimdDirective &S,
4250 PrePostActionTy &Action) {
4251 Action.Enter(CGF);
4252 // Emit directive as a combined directive that consists of two implicit
4253 // directives: 'parallel' with 'for' directive.
4254 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4255 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4256 emitDispatchForLoopBounds);
4257 };
4258 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4259 emitEmptyBoundParameters);
4260}
4261
4262void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4263 CodeGenModule &CGM, StringRef ParentName,
4264 const OMPTargetParallelForSimdDirective &S) {
4265 // Emit SPMD target parallel for region as a standalone region.
4266 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4267 emitTargetParallelForSimdRegion(CGF, S, Action);
4268 };
4269 llvm::Function *Fn;
4270 llvm::Constant *Addr;
4271 // Emit target region as a standalone region.
4272 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4273 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4274 assert(Fn && Addr && "Target device function emission failed.");
4275}
4276
4277void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4278 const OMPTargetParallelForSimdDirective &S) {
4279 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4280 emitTargetParallelForSimdRegion(CGF, S, Action);
4281 };
4282 emitCommonOMPTargetDirective(*this, S, CodeGen);
4283}
4284
Alexey Bataev7292c292016-04-25 12:22:29 +00004285/// Emit a helper variable and return corresponding lvalue.
4286static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4287 const ImplicitParamDecl *PVD,
4288 CodeGenFunction::OMPPrivateScope &Privates) {
4289 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4290 Privates.addPrivate(
4291 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4292}
4293
4294void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4295 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4296 // Emit outlined function for task construct.
4297 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4298 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4299 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4300 const Expr *IfCond = nullptr;
4301 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4302 if (C->getNameModifier() == OMPD_unknown ||
4303 C->getNameModifier() == OMPD_taskloop) {
4304 IfCond = C->getCondition();
4305 break;
4306 }
4307 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004308
4309 OMPTaskDataTy Data;
4310 // Check if taskloop must be emitted without taskgroup.
4311 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004312 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004313 Data.Tied = true;
4314 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004315 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4316 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004317 Data.Schedule.setInt(/*IntVal=*/false);
4318 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004319 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4320 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004321 Data.Schedule.setInt(/*IntVal=*/true);
4322 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004323 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004324
4325 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4326 // if (PreCond) {
4327 // for (IV in 0..LastIteration) BODY;
4328 // <Final counter/linear vars updates>;
4329 // }
4330 //
4331
4332 // Emit: if (PreCond) - begin.
4333 // If the condition constant folds and can be elided, avoid emitting the
4334 // whole loop.
4335 bool CondConstant;
4336 llvm::BasicBlock *ContBlock = nullptr;
4337 OMPLoopScope PreInitScope(CGF, S);
4338 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4339 if (!CondConstant)
4340 return;
4341 } else {
4342 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4343 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4344 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4345 CGF.getProfileCount(&S));
4346 CGF.EmitBlock(ThenBlock);
4347 CGF.incrementProfileCounter(&S);
4348 }
4349
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004350 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4351 CGF.EmitOMPSimdInit(S);
4352
Alexey Bataev7292c292016-04-25 12:22:29 +00004353 OMPPrivateScope LoopScope(CGF);
4354 // Emit helper vars inits.
4355 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4356 auto *I = CS->getCapturedDecl()->param_begin();
4357 auto *LBP = std::next(I, LowerBound);
4358 auto *UBP = std::next(I, UpperBound);
4359 auto *STP = std::next(I, Stride);
4360 auto *LIP = std::next(I, LastIter);
4361 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4362 LoopScope);
4363 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4364 LoopScope);
4365 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4366 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4367 LoopScope);
4368 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004369 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004370 (void)LoopScope.Privatize();
4371 // Emit the loop iteration variable.
4372 const Expr *IVExpr = S.getIterationVariable();
4373 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4374 CGF.EmitVarDecl(*IVDecl);
4375 CGF.EmitIgnoredExpr(S.getInit());
4376
4377 // Emit the iterations count variable.
4378 // If it is not a variable, Sema decided to calculate iterations count on
4379 // each iteration (e.g., it is foldable into a constant).
4380 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4381 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4382 // Emit calculation of the iterations count.
4383 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4384 }
4385
4386 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4387 S.getInc(),
4388 [&S](CodeGenFunction &CGF) {
4389 CGF.EmitOMPLoopBody(S, JumpDest());
4390 CGF.EmitStopPoint(&S);
4391 },
4392 [](CodeGenFunction &) {});
4393 // Emit: if (PreCond) - end.
4394 if (ContBlock) {
4395 CGF.EmitBranch(ContBlock);
4396 CGF.EmitBlock(ContBlock, true);
4397 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004398 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4399 if (HasLastprivateClause) {
4400 CGF.EmitOMPLastprivateClauseFinal(
4401 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4402 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4403 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4404 (*LIP)->getType(), S.getLocStart())));
4405 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004406 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004407 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4408 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4409 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004410 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4411 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004412 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4413 OutlinedFn, SharedsTy,
4414 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004415 };
4416 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4417 CodeGen);
4418 };
Alexey Bataev33446032017-07-12 18:09:32 +00004419 if (Data.Nogroup)
4420 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4421 else {
4422 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4423 *this,
4424 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4425 PrePostActionTy &Action) {
4426 Action.Enter(CGF);
4427 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4428 },
4429 S.getLocStart());
4430 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004431}
4432
Alexey Bataev49f6e782015-12-01 04:18:41 +00004433void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004434 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004435}
4436
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004437void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4438 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004439 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004440}
Samuel Antao686c70c2016-05-26 17:30:50 +00004441
4442// Generate the instructions for '#pragma omp target update' directive.
4443void CodeGenFunction::EmitOMPTargetUpdateDirective(
4444 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004445 // If we don't have target devices, don't bother emitting the data mapping
4446 // code.
4447 if (CGM.getLangOpts().OMPTargetTriples.empty())
4448 return;
4449
4450 // Check if we have any if clause associated with the directive.
4451 const Expr *IfCond = nullptr;
4452 if (auto *C = S.getSingleClause<OMPIfClause>())
4453 IfCond = C->getCondition();
4454
4455 // Check if we have any device clause associated with the directive.
4456 const Expr *Device = nullptr;
4457 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4458 Device = C->getDevice();
4459
Alexey Bataev7828b252017-11-21 17:08:48 +00004460 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4461 PrePostActionTy &) {
4462 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4463 Device);
4464 };
4465 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4466 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_update,
4467 CodeGen);
Samuel Antao686c70c2016-05-26 17:30:50 +00004468}